After some digging and a little more thought I find that removing this
comment from the example in the docs at
www.php.net/language.operators.precedence does indeed cause more harm than
good. So I'm definitely wrong in saying that it should be removed.

However, I would like to acknowledge the confusion evident in bug 65087 and
offer some clarifying language and examples that may assist future users as
well as bring some closure to this bug report.

As pointed out to me on IRC PHP has exhibited changes in this behavior
between PHP < 5.1.0 and PHP >= 5.1.0 where the order of evaluation is not
well-defined. The example states that  ++$a + $a++ may result in 4 or 5 and
that the behavior is undefined. This by itself seems confusing to the user
since they always see 4. What's not clear is that this isn't typical
everywhere in PHP.

For example:

$i = 0;
$i = $i++;

Here $i is always 0, but again the behavior is undefined because in the
following code it is not clear what happens:

$i = 0;
$arr = array();
$arr[$i] = $i++;
var_dump($arr);

According to  the above code produces the following result between PHP
4.3.1 and 5.5.1

array(1) { [0]=> int(0) }

Where as the same code produces a very different result between PHP 5.1.0
and above:

array(1) { [1]=> int(0) }

The same happens with preinc/dec operators as well

$i = 0; $arr = array(); $arr[$i] = ++$i; var_dump($arr);

PHP < 5.1.0

array(1) { [0]=> int(1) }

PHP >= 5.1.0

array(1) { [1]=> int(1) }


The problem is I'm not sure where this type of information should be
documented. It makes sense to put this on the increment/decrement operators
page, but doesn't seem appropriate the operator precedence page. So to make
sure we're all in agreement I'm suggesting the following language to be
added as a note on the increment/decrement operators page at
www.php.net/language.operators.increment with supplement examples provided
above to help users get a better understanding of what we mean when we say
undefined behavior and add an additional warning box not to rely on this
type of behavior.

"As noted from the examples above the use of multiple increment/decrement
operators in the same expression is considered undefined behavior because
the order of evaluation cannot be guaranteed. Using such evaluations may
lead to unexpected results."

"Warning:
Relying on this behavior is discouraged as it may be subject to change and
without notice. Results are not typical and are implementation-specific."

If anyone feels that could use a little more clarity or can be reworded
better let me know. Thanks.

Reply via email to