Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go back at the beginning of a foreach loop in PHP

Tags:

foreach

php

Is it possible ? Or should I end the loop and beginning another ?

foreach($array as $i)
{
    if (something)
        // Go back
}
like image 773
Zooly Avatar asked May 22 '15 07:05

Zooly


People also ask

What is a foreach loop in PHP?

The foreach loop - Loops through a block of code for each element in an array. The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

How do you loop through an array in PHP?

PHP foreach loop is utilized for looping through the values of an array. It loops over the array, and each value for the fresh array element is assigned to value, and the array pointer is progressed by one to go the following element in the array.

Is it possible to restart a foreach loop?

You can't restart a foreach, no. @techie_28 form the required array in PHP first, then use json_encode. (and keep working on improving your english, it will help you greatly!) Show activity on this post. See more here.

How to iterate over an array in PHP?

The foreach loop in PHP construct produces the most comfortable way to iterate the array components. It runs on arrays and objects both. The foreach loop iterates over an array of entities; the enactment is streamlined and completes the loop in a limited time comparatively.


1 Answers

It is. But not with foreach & without leaving the loop. Here's another alternative, for good measure.

for ($i = 0; $i < count($array); $i++) {
  if (condition) {
    $i = 0;
  }
  do_stuff_with($array[$i]);
}
like image 128
Alex M Avatar answered Oct 12 '22 00:10

Alex M