RSS
 

PHP Order of Operations Gotcha

04 Sep

PHP’s decision to give addition, subtraction and string concatenation equal precedence has caused some difficult to track down bugs on several occasions. It’s so non-intuitive I have difficulty remembering this one, and hence keep writing wrong code.

Example:

$tacos = "Robots: " . 1 + 2 . " for the win!";

I think a normal human would expect $tacos to be equal to “Robots: 3 for the win!”. But the result is actually “2 for the win!”

What gives? Well, the PHP docs say that plus, minus and string concatenation all get equal precedence, with left associativity. So going from left to right, it says:
“Robots: ” . 1 | “Robots: 1” so far, so good.
“Robots: 1″ + 2 => (int)”Robots: 1” + 2; | “Robots: 1″ converts to 0, so 0 + 2
2 . ” for the win!” | “2 for the win!” D’oh!

I think it would make a lot more sense for string concatenation to take a lower precedence than any arithmetic.

The correct way to write the above code is:

$tacos = "Robots: " . (1 + 2) . " for the win!";

 
3 Comments

Posted in Coding

 

Leave a Reply

 

 
  1. James Hartig

    September 4, 2009 at 2:14 pm

    Well, it doesn’t work well there, but I have used it many times the other way where I wanted to add a variable to a number then add that to another set.

     
  2. Jay

    September 4, 2009 at 2:38 pm

    True, half the time PHP will decide to store your int as a string anyway. But having addition take precedence over concatenation shouldn’t interfere with that…

     
  3. Myke Stubbs

    November 29, 2009 at 7:43 pm

    @James: It does pretty well with variables and operands in scenarios like this. But do you really want to trust it given the example?

    Read: This is why we love to hate Python ;)

    My 0.02