Reputation: 13
My Question is why does the post increment not function on the first element but then works as expected when it is contained within an array [ ] element ?
Here is a snippet of what I was doing that behaves unexpectedly:
When I use this code ...
$lessonIndex = 0;
$EventArray[$lessonIndex]['Title'] = 'Lesson 1';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex++]['Title']]['Start'];
$EventArray[$lessonIndex]['Title'] = 'Lesson 2';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex++]['Title']]['Start'];
$EventArray[$lessonIndex]['Title'] = 'Lesson 3';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex++]['Title']]['Start'];
The $EventArray[$lessonIndex] contents will be skip index 0 then index 1 will get what was destined for index 0 and the increment proceeds as expected through the rest of the code, but with the results being off by one.
If I do this instead:
$lessonIndex = 0;
$EventArray[$lessonIndex]['Title'] = 'Lesson 1';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex]['Title']]['Start'];
$lessonIndex++;
$EventArray[$lessonIndex]['Title'] = 'Lesson 2';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex]['Title']]['Start'];
$lessonIndex++;
$EventArray[$lessonIndex]['Title'] = 'Lesson 3';
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex]['Title']]['Start'];
$lessonIndex++;
Everything works as expected.
Upvotes: 1
Views: 312
Reputation: 39773
$EventArray[$lessonIndex]['Start'] = $TimeArray[$EventArray[$lessonIndex++]['Title']]['Start'];
What happens is that
=
) gets
evaluated.$lessonIndex
will get incremented.$lessonIndex
has already been incremented.So this would be equal to writing
$lessonIndex = 0;
$EventArray[$lessonIndex]['Title'] = 'Lesson 1';
$somevalue = $TimeArray[$EventArray[$lessonIndex]['Title']]['Start'];
$lessonIndex++;
$EventArray[$lessonIndex]['Start'] = $somevalue;
Upvotes: 1
Reputation: 360922
PHP has order of operations. The ++
is evaluated BEFORE PHP calculates what array index you're referring to. So you increment the value, THEN that new value is returned and used as the array index.
$a = 0;
$x = $arr[$a++];
is functionally identical to
$a = 0;
$a++;
$x = $arr[$a]; // aka $arr[1];
Upvotes: 0
Reputation: 28936
In your first example, the ++
operator incremented the value, then sent the result as the array index.
In your second example, the value was sent as the array index, then incremented.
Upvotes: 1