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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cmega
Forum Newbie
Posts: 4
Joined: Wed May 28, 2003 9:28 am

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

Post 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!
User avatar
patrikG
DevNet Master
Posts: 4235
Joined: Thu Aug 15, 2002 5:53 am
Location: Sussex, UK

Post 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 :)
User avatar
nielsene
DevNet Resident
Posts: 1834
Joined: Fri Aug 16, 2002 8:57 am
Location: Watertown, MA

Post 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?
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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)
cmega
Forum Newbie
Posts: 4
Joined: Wed May 28, 2003 9:28 am

Post by cmega »

Thank you volka - ksort() did the trick.
Post Reply