Page 1 of 1

foreach and define() - why doesn't this work as intended?

Posted: Wed May 28, 2003 9:28 am
by cmega
Why don't defined constants work as expected?

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 => 111
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:

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 => 333
Why do defined constants behave differently than the constants they represent?

Thank you!

Posted: Wed May 28, 2003 9:56 am
by patrikG
Simply because in your example 2 you have an indexed(!) array, hence the ordered output.

Constants don't have an index per se (your example 1), they just remain constant.

That's why defined constants work as expected.

That's my hypothesis, anyway :)

Posted: Wed May 28, 2003 10:20 am
by nielsene
Just a guess, perhaps the
define(SECOND,2);
$test[SECOND] actually evaluates to $test["2"] so its a string 2 not a number 2?

Posted: Wed May 28, 2003 10:45 am
by volka
an array is not an (key-)ordered list, but a random access array (ok, it's a hash but still not an ordered one ;) )
you might be interested in http://php.net/ksort (and the other sort functions as well)

Posted: Thu May 29, 2003 11:10 am
by cmega
Thank you volka - ksort() did the trick.