Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bug in PHP array index assignment?

Status
Not open for further replies.

beakerboy

Technical User
May 31, 2001
27
0
0
US
I'm running PHP 5.2.9-2

PHP:
	$year1=$year2=$year3=2009;
while ($year1 <= date('Y')){
  $array1[$year1] = $year1 . "-" . ++$year1;
  $array2[$year2+0] = $year2 . "-" . ++$year2;
  $array3[$year3+1] = $year3 . "-" . ++$year3;	
}
print_r($array1);
print_r($array2);
print_r($array3);

Produces the following:
PHP:
Array
(
    [2010] => 2009-2010
    [2011] => 2010-2011
    [2012] => 2011-2012
    [2013] => 2012-2013
)
Array
(
    [2009] => 2009-2010
    [2010] => 2010-2011
    [2011] => 2011-2012
    [2012] => 2012-2013
)
Array
(
    [2010] => 2009-2010
    [2011] => 2010-2011
    [2012] => 2011-2012
    [2013] => 2012-2013
)

You would think the first two would be equivalent, but instead the first and third are. Is this a bug or a feature. If a bug, is it still in the current version? If assuming the array index name is being evaluated last in the first case, and first in the send two cases.

Kevin
 
Looks to me like just a difference of evaluation times.

In the first line the array key, is not evaluated until after the contents are.

That is it runs the code "$year1 . "-" . ++$year1;" first before attempting to stick it inside the array. Since there is nothing to evaluate in the key it waits for the contents to be evaluated before checking the key value. $year1. Except by then, $year1 has been increased by 1.

For the other 2 it seems to be evaluating the array key before evaluating the contents. So the value of year2 and year3 has not yet had a chance to be changed. I'm guessing this happens because the array jey in both cases is an operation. While in the first case its merely a value from the variable.

I'm guessing its a feature rather than a bug. Different evaluation times depending on the key.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top