Re: Going through 2 arrays at once

From: Date: Wed, 24 May 2006 02:56:23 +0000
Subject: Re: Going through 2 arrays at once
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-236795@lists.php.net to get a copy of this message
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

« previous php.general (#236795) next »