Jump to content

Simple question about addition of two numbers.


claudiogc

Recommended Posts

You somehow assume that addition takes precedence over string concatenation, but that's not the case. They have equal precedence and are evaluated from left to right.

 

It's generally a bad idea to rely on the internal precedence of operators (except maybe for obvious cases like addition and multiplication). Use parentheses. 

If is the case why is he not showing "Addition: 4"? Because he should concat "Addition" with "4" and after that i have no idea.

If you evaluate it one operator at a time and sub the results into the original equation you can see what happens.

echo 'Addtion: ' . $x + $y . '<br>';
Evaluate the first . operator, result is: 'Addition: 4', so then you have:

echo 'Addtion: 4' + $y . '<br>';
Evaluate the + operator. PHP try and convert the first operand to a number but since the string is not a valid number you get zero. Now you have:

echo 2 . '<br>';
Which gives you a final output of '2<br>';

 

 

PHP try and convert the first operand to a number but since the string is not a valid number you get zero.

Did not understand this part.

"PHP try and convert the first operand to a number"

The number 2? Because the real first operand of the operation, number 4, already is part of the other string. What happened to "+"?

 

"but since the string is not a valid number you get zero."

What string?

The + operator applies to 'Addition: 4' and 2. 'Addition: 4' is a string, not a number so PHP will attempt to convert it. Since it is not possible to convert it however you end up with zero so the end result is you have 0 + 2.

Step 1:
echo [ "Addtion: " . $x ] + $y . "<br>";
 
PHP CONCATENATES the String "Addition" and the number 4 creating the string "Addition: 4", which results in:
echo "Addtion: 4" + $y . "<br>";
 
 
//Step 2:
echo [ "Addtion: 4" + $y ] . "<br>";
 
PHP ADDS the string "Addition: 4" with the number 2 Since the string is not a number, PHP converts it to one. Since it begins with an alpha character it converts it to 0. Thus, you get [ 0 + 2]. Result:
echo 2 . "<br>";
 
Step 3:
echo [ 2 . "<br>" ];
 
PHP CONCATENATES the Number 2 and the string "<br>"
Result
 
echo "2 <br>";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.