<?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.
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
$currentYearvalue 2012 and increment by 1. Then it comes to the RHS takes$currentYearvalue and assigns it to the array options with the key 2012. Likewise, it continues with the iteration.