Reputation: 377
Let's say I'm trying to combine items from two lists, and I want to get this result:
A7
A8
B7
B8
This is my code:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list( , $item1) = each($list1_array)) {
while(list( , $item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
}
?>
I get this result:
A7
A8
I seems like outside 'while' doesn't make the second loop? What am I doing wrong?
Upvotes: 0
Views: 1367
Reputation: 116100
Why not use foreach?
foreach ($list1_array as $item1)
{
foreach ($list2_array as $item2)
{
echo $item1.$item2."<br />";
}
}
Using a while
loop with each
makes the loop depend on the array pointer. An array has a pointer that tells you which item is the 'current' one. You can use functions like current
to get the current item in the array. each
is also such a function. It returns the current item (or actually an array with the key and value of the current item).
And therein lies the problem. The inner while loop stops when you are at the end of the array. So for the first item of the outer array (array1), the inner while loop (array2) runs fine. But the second time, the pointer is still at the end of the array and each
returns false right away.
So, the solution could be to reset the array pointer, using the reset
function as sharply pointed out by @summea. Or you can use a foreach
loop, which is not affected by this fenomenon, because it resets the array pointer itself when it starts. Also, I this it's more readable, especially due to the weird list
construct. Nevertheless, it might be good to know how the internals work, and your while
loop works more low-level than foreach
.
Upvotes: 3
Reputation: 7583
While it might be better to use a slightly more common (perhaps more readable) approach (e.g. by using foreach
loops as shown by GolezTrol,) in answer to your original questions:
The problem is most likely happening because the internal "cursor" (or "pointer") for your array is not being reset
... so it never gets back to the start of the original array.
Instead, what if you try something like this:
<?php
$list1_array = array('A', 'B');
$list2_array = array('7', '8');
while(list(,$item1) = each($list1_array)) {
while(list(,$item2) = each($list2_array)) {
echo $item1.$item2."<br />";
}
reset($list2_array);
}
?>
Upvotes: 3