Question

<?php
$options = array();
$currentYear = 2012;

while($currentYear < (2012 + 3) ) {
    $options[$currentYear++] = $currentYear;
}

var_dump($options);
?>

expected output:

array(3) {
     [2012]=> int(2012)
     [2013]=> int(2013)
     [2014]=> int(2014)
}

Generic theory: Executes the RHS of an assignment first and assigns the RHS value to LHS. It would execute post-increment in LHS after it executed the RHS. According to this scenario, we can explain the iteration as follows.

In 1st iteration, RHS $currentYear value is 2012 and assigns that value to array options with key 2012. Increment the variable $currentYear by 1, and proceed with the iteration. In 2nd iteration, RHS $currentYear value is 2013 and assigns that value to array options with key 2013. Increment the variable $currentYear by 1, and proceed with the iteration. What happened to this generic programming concept down below?

Actual output:

 array(3) {
     [2012]=> int(2013)
     [2013]=> int(2014)
     [2014]=> int(2015)
 }

If someone can come up with a better explanation that would be great, and much appreciate.

Was it helpful?

Solution

Above theory is wrong. In PHP arrays have higher precedence than increment/decrement. Therefore PHP executes the array keys first (that's why first element of the array key appeared as 2012) and then goes to the assignment.

In this scenario, PHP keeps array key as $currentYear value 2012 and increment by 1. Then it comes to the RHS takes $currentYear value and assigns it to the array options with the key 2012. Likewise, it continues with the iteration.

OTHER TIPS

Try to keep in mind the concepts of Incrementing/Decrementing Operators and you will understand better these operators.

Post-increment returns $currentYear, then increments $currentYear by one, based in this, what is happening in your case is the following:

$currentYear = 2012;

$options[$currentYear++] = $currentYear;

/* Post-increment will return 2012 to the array, after this will increment it to 
 * 2013, so in the right side it will be 2013, then you'll get the result below. 
 * Remember that PHP analyses the code from left to right.
 */

$options[2012] == 2013;

To get your expected result you must use pre-increment because it will increment $currentYear by one, then returns $currentYear. For instance:

$currentYear = 2012;

$options[++$currentYear] = $currentYear;

/* Pre-increment will increment $currentYear first, after this will return the 
 * value to array, so $currentYear will have the same value in both sides. 
 * Like below.
 */

$options[2013] == 2013;

EDIT 1

As your first index and $currentYear must be equals you must use a different logic, something like this:

$options = array();
$currentYear = 2012;

while($currentYear < (2012 + 3) ) {
    $options[$currentYear] = $currentYear;

    $currentYear++; // "++$currentYear" and "$currentYear += 1" will work too
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top