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. 

Edited by Jacques1
  • Like 1
Link to comment
Share on other sites

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>';
  • Like 1
Link to comment
Share on other sites

 

 

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?

Link to comment
Share on other sites

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>";

Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.