RE: Going through 2 arrays at once

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

 



Thanks for all the replies guys, it really helped me pick up a few
things.

One I ended up doing was using array_combine, like so:

$d = array_combine($arrLogDrive, $logicalDrive); 
print_r($d);
for (reset($d); $j = key($d); next($d)) {
        echo "$j: $d[$j]<br />\n";
}  

Now, while it works spot on for me, since no one suggested it I assume
I'm not using it in it's greatest capacity and will look at other
methods. But hey, at least it works, I'm happy about that! 

-----Original Message-----
From: David Tulloh [mailto:david@xxxxxxxxxxxx] 
Sent: Tuesday, May 23, 2006 9:56 PM
To: Pavleck, Jeremy D.
Cc: PHP LIST
Subject: Re:  Going through 2 arrays at once

Pavleck, Jeremy D. wrote:

> how do I go through 2 arrays at
> once with different keys? 
> 

> for ( $i = 0; $i < sizeof($logicalDrive); $i++) {
>         echo "$arrLogDrive[$i]<br />\n"; }
> 
> for (reset($logicalDrive); $i = key($logicalDrive); 
> next($logicalDrive)) {
>         echo "$i: $logicalDrive[$i]<br />\n"; }

The slight complication here is that you are iterating through an
indexed and an associative array.  There are two easy solutions,
building on each of the above loops.

As you don't care about the key of the second array you can convert it
to an indexed array using array_values().

$logicalDrive_indexed = array_values($logicalDrive); for($i=0;
$i<min(sizeof($arrLogDrive), sizeof($logicalDrive)); $i++) {
    echo $arrLogDrive[$i].": ".$logicalDrive[$i]."<br />\n"; }

Alternatively the next() function works for indexed arrays.

for(reset($arrLogDrive), reset($logicalDrive);
current($arrLogDrive)!==false && current($logicalDrive)!==false;
next($arrLogDrive), next($logicalDrive)) {
    echo current($arrLogDrive).": ".current($logicalDrive)."<br />\n"; }

The second approach will have problems if either of the arrays contain
the value false.  Personally I would use the first loop.


David

-- 
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