Re: Going through 2 arrays at once

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

 



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