foreach and define() - why doesn't this work as intended?
Posted: Wed May 28, 2003 9:28 am
Why don't defined constants work as expected?
Why doesn't the $myvar array print in numeric ordinal order, ie.,
1 => 111
2 => 222
3 => 333
If you assign using numeric indices, in any order, rather than using the defined constants, it works fine:
Why do defined constants behave differently than the constants they represent?
Thank you!
Code: Select all
define (FIRST, 1);
define (SECOND, 2);
define (THIRD, 3);
// note order of assignment below
$myvar[SECOND] = 222;
$myvar[THIRD] = 333;
$myvar[FIRST] = 111;
foreach ($myvar as $key => $val) {
print "<BR>". $key . " => " . $val;
}
PRODUCES:
2 => 222
3 => 333
1 => 1111 => 111
2 => 222
3 => 333
If you assign using numeric indices, in any order, rather than using the defined constants, it works fine:
Code: Select all
// again note order of assignment
$myvar[2] = 222;
$myvar[3] = 333;
$myvar[1] = 111;
foreach ($myvar as $key => $val) {
print "<BR>". $key . " => " . $val;
}
produces the correctly ordered output.
1 => 111
2 => 222
3 => 333Thank you!