Using more than one array in loop in PHP

Usually we use foreach loop when there is a need to use only one array. But what if there are more than one array…

Foreach loop works only with a single array. To step through multiple arrays it’s better to use the each() function in a while loop. Have a look at it..

while(($code = each($codes)) && ($name = each($names))) {
echo '<option value="' . $code['value'] . '">' . $name['value'] . '</option>';

each() returns information about the current key and value of the array and increments the internal pointer by one, or returns false if it has reached the end of the array. This code would not be dependent upon the two arrays having identical keys or having the same sort of elements. The loop terminates when one of the two arrays is finished.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s