Iterating over parallel arrays using each()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I looked for a little while and didn't find any elegant solutions for doing this, so first if you have alternate suggestions for the "right" way to do this, I'd love to hear them. I'm working with a big form to allow a user to make a change to many database rows at the same time. The results are getting passed to a PHP script to do the updates, as three different HTML arrays (i.e., <input name='var1[]'>). While I could do a normal for loop and just go through each array by its numerical index, the first thing I tried was using each() on all three arrays. After seeing some weird results, I made a shorter test script that illustrates the same problem I've been having.

The problem seems to be that when each() is called multiple times on different arrays within the same expression, only the last call to each() assigns its variable correctly. (The other two print_r statements within the loop show up as the '1's before the array is printed.)

Any thoughts on why this is happening? Is it a bug, or am I just expecting PHP/while/each to do things that they're not actually supposed to do?

-brian


------------
--- Code ---
------------

<?php
$letters = array('a','b','c');
$numbers = array(1,2,3);
$bigletters = array('A','B','C');

echo "\n\nOutside of the loop\n\n";

$let = each($letters);
$num = each($numbers);
$cap = each($bigletters);

print_r($let);
print_r($num);
print_r($cap);

echo "\n\nInside the loop\n\n";

reset($letters);
reset($numbers);
reset($bigletters);

while($let = each($letters) && $num = each($numbers) &&
        $cap = each($bigletters)) {
    print_r($let);
    print_r($num);
    print_r($cap);
    echo "<br><br>\n";
}

?>

--------------
--- Output ---
--------------

Outside of the loop

Array
(
    [1] => a
    [value] => a
    [0] => 0
    [key] => 0
)
Array
(
    [1] => 1
    [value] => 1
    [0] => 0
    [key] => 0
)
Array
(
    [1] => A
    [value] => A
    [0] => 0
    [key] => 0
)


Inside the loop

11Array
(
    [1] => A
    [value] => A
    [0] => 0
    [key] => 0
)
<br><br>
11Array
(
    [1] => B
    [value] => B
    [0] => 1
    [key] => 1
)
<br><br>
11Array
(
    [1] => C
    [value] => C
    [0] => 2
    [key] => 2
)
<br><br>

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux