Axalix Axalix -3 years ago 60
PHP Question

Why does the PHP parser understand "$x++-++$x", but fail on "$x+++++$x"?

I have an engine that does some mathematical and logical operations by taking formulas, operands and operators from a file.
All the operations are executed in an

eval
scope and the final result is saved in another file.

These files are often transferred through a network, so I am trying to minimize them by stripping all the spaces before and after operations.
As far as I know there are no strict rules about that matter, however I stumbled upon this behavior:



$x = 1;
$result = $x++-++$x; // works
$result = $x+++++$x; // fails
$result = $x++ + ++$x; // works again



  1. Why is PHP confused by the "+++++" syntax, but accepts "++-++"? How
    is "plus" better than "minus"?

  2. Is there a list anywhere of operators that are sensitive
    about spaces?


Answer Source

The PHP parser is searching for the ++ sign before the last + sign, and the syntax ($x++)++ makes no sense, due to the fact that the increment operator should be applied to a variable (and not an integer, which is the result of the first $x++).

The precedence of the operator's operations can be found here:
http://php.net/manual/en/language.operators.precedence.php

$x+++++$x;
^ php parser starts here, find $x++
    ^ here there is a new ++, which has hight precedence to the next + char
      ^ here is the last +, which the php parser will find last.

When the two ++, ++ split with a minus sign, the code is actually $x++ - ++$x, one which the PHP parser can understand.

This is also the reason why $x++ + ++$x works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download