422
422

Reputation: 5770

adding two vars together ( php )

I have these two vars, one to display facebook count and one to display twitter count.

so.

To display twitter and facebook count I use.

echo "Latest Tweet Count " . $obj->get_tweets() . "<br />"; //to get tweets
echo "Latest Facebook Count " . $obj->get_fb() . "<br />"; //to get facebook total count

I want to ADD the count together to show total.

I tried.

echo "Total Twitter and FB Count " .$obj->get_tweets()+$obj->get_fb() . "<br />";

But isnt working, any idea what I am doing wrong.

Upvotes: 1

Views: 76

Answers (3)

inorganik
inorganik

Reputation: 25535

It's important to know what type of object your dealing with. Adding two strings like "43"+"86" won't work. Nor can you add two arrays. But you want a number so you have to get a number value from your object.

If the object is an array

count($obj->get_tweets())

If it is a string of a number, like "43" instead of 43

intval($obj->get_tweets())

Upvotes: 2

cy834sh4rk
cy834sh4rk

Reputation: 101

Try assigning the returned values of get_tweets() and get_fb() to variables.

    $tweets = $obj->get_tweets();
    $fbs    = $obj->get_fb();
    $total  = $tweets + $fbs;
    echo "Total Twiter and FB count: $total <br />";

This is assuming that both get_tweets() and get_fb() return integers.

Upvotes: 2

Emissary
Emissary

Reputation: 10148

If you really must mix logic with your "view" then you need to be mindful of the order of operations - i.e. you want to ensure that the sum of your operands is evaluated before either side is concatenated with the rest of the string. You can achieve this by explicitly wrapping the expression in parenthesis...

echo "Total... ". ( $obj->get_tweets() + $obj->get_fb() ) ."<br />";
//                ^_____________________________________^

Upvotes: 2

Related Questions