Reputation: 20049
I'm trying to work out how to continuously loop through an array, but apparently using foreach
doesn't work as it works on a copy of the array or something along those lines.
I tried:
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
reset($stuff);
}
}
But obviously that didn't work. What are my choices here?
Upvotes: 1
Views: 2714
Reputation: 140
Here's one using reset() and next():
$total_count = 12;
$items = array(1, 2, 3, 4);
$value = reset($items);
echo $value;
for ($j = 1; $j < $total_count; $j++) {
$value = ($next = next($items)) ? $next : reset($items);
echo ", $value";
};
Output:
1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
I was rather surprised to find no such native function. This is a building block for a Cartesian product.
Upvotes: 3
Reputation: 1309
You could use a for
loop and just set a condition that's always going to be true - for example:
$amount = count($stuff);
$last_key = $amount - 1;
for($key=0;1;$key++)
{
// Do stuff
echo $stuff[$key];
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
$key= -1;
}
}
Obviously, as other's have pointed out - make sure you've got something to stop the looping before you run that!
Upvotes: 1
Reputation: 9552
This loop will never stop:
while(true) {
// do something
}
If necessary, you can break your loop like this:
while(true) {
// do something
if($arbitraryBreakCondition === true) {
break;
}
}
Upvotes: 3
Reputation: 17205
Using a function and return false in a while loop:
function stuff($stuff){
$amount = count($stuff);
$last_key = $amount - 1;
foreach ($stuff as $key => $val) {
// Do stuff
if ($key == $last_key) {
// Reset array cursor so we can loop through it again...
return false;
}
}
}
while(stuff($stuff)===FALSE){
//say hello
}
Upvotes: 0
Reputation: 76646
You can accomplish this with a while
loop:
while (list($key, $value) = each($stuff)) {
// code
if ($key == $last_key) {
reset($stuff);
}
}
Upvotes: 4
Reputation: 51950
An easy way is to combine an ArrayIterator with an InfiniteIterator.
$infinite = new InfiniteIterator(new ArrayIterator($array));
foreach ($infinite as $key => $val) {
// ...
}
Upvotes: 5