I have to iterate over an array and I can't decide which is the 'better' way. Theres a few different constructs that allow for this. Firstly... I can do something simple like..

while($row = current($arr)) {
$row["my_col"];
next($arr);
}

which stops if $row is 0 or "0" i believe.

next is the list, each methods...

while(list($key, $val) = each($arr)) {
echo "$key is $val";
}

finally, in PHP4 .. there is the foreach construct...

foreach($arr as $key => $val) {
echo "$key is $val";
}

I realize this is pretty much the same as using list / each... but is there perhaps a reason to choose one over the other? manual says foreach uses a copy of the array (but i'm assuming the while list/each does the same)..[althought I'm a little unsure about the foreach looping each entry twice.. one for numeric index and one for associative index]

Is there a more accepted practice?

    I do not use list()/each(), I dont have any reason other then I find foreach simpler and easier to read.

    foreach() does make a copy, in future versions you will be able to do a reference to the orig array, this will be nice.

    foreach($array as $pos => &$val)

    foreach does not loop throught the array twice as you may beleive. unless I am missunderstanding you.

    $test['a'] = 'a';
    $test['b'] = 'b';
    $test['c'] = 'c';

    this array has only 3 elements. php does not accually have numeric indexes, all arrays in php are asosiative. an array with number indexes are just asosiative indexes with the index names as numbers.

    back to our example.

    there are only 3 valid elements in this array.

    $test[0]
    $test[1]
    $test[2]

    are all invalid, they do not exisit.

    back again, this means foreach only loops though assosiative indexes because thats all there is.

    Chris Lee
    lee@mediawaveonline.com

      Write a Reply...