note 110914 deleted from language.operators.increment by danbrown
| From: | danbrown@php.net | Date: | Thu, 17 Jan 2013 15:31:18 +0000 |
| Subject: | note 110914 deleted from language.operators.increment by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193155@lists.php.net to get a copy of this message | ||
Note Submitter: erich at seachawaii dot com
----
Regarding post increment and decrement in the index of an array (and I assume strings) used in
assignment and expression to be assigned: Assignment index expressions and value expressions are
both evaluated before any actual assignment happens, that means that no mater where you place your
post incr/decr you may not be getting the result you had in mind. The following example shows this.
$a = [ 0, 1, 2 ];
$i = 0;
$a[$i++] = $i;
var_dump( $a );
/* renders: ( note element [initial value $i as 0] is assign to [after incr value $i as 1] as I
would not expect )
array (size=3)
0 => int 1
1 => int 1
2 => int 2
*/
$a = [ 0, 1, 2 ];
$i = 0;
$a[$i] = $i++;
var_dump( $a );
/* renders: ( note element [after incr value $i as 1] is assign to [initial value $i as 0] as
expected )
array (size=3)
0 => int 0
1 => int 0
2 => int 2
*/
There is a note on this already, but it doesn't really explain the problem and the sample code
is missing initial values, so I am posting this because it is more to the point and clearer.