How to force foreach reset in php

Is it possible in php to reset Foreach?

eg:

foreach($rows as $row)
{
  if(something true)
  {
     continue foreach;
  }
  else
  {
     break;
     reset foreach;//I mean start foreach again...
  }
}

---------------------------------- Edited

Thanks to my friend for your answers ...

The condition is generated from the foreach result, so I cannot use the function. I wana sort it by (example) alphabet ... in many div html. I cannot filter the result by SQL for the same resonance.

So I have to use the css trick.

+4
source share
5 answers

You can do something around these lines (and avoid recursion restrictions):

while (True) {
    $reset = False;
    foreach ($rows as $row) {
      if(something true) {
         continue;
      } else {
          $reset = True;
          break;
      }
    }
    if ( ! $reset ) {
        break; # break out of the while(true)
    }
    # otherwise the foreach loop is `reset`
}
+2
source

It seems that resetinside a foreachhas no effect.

This can be implemented if you create your own Traversable.

+2

, , , .

function doForEach($rows) {
    foreach($rows as $row)
    {
        if(something true)
        {
            continue foreach;
        }
        else
        {
            break;
            doForEach($rows);
        }
    }
}

, , , .

+1

Why reset foreach? If you really need it ... But take care of the infinite loop!

function myForeach($array){
    foreachforeach($rows as $row){
        if(something true){
           continue foreach;
        }else{
           myForeach($array);
        }
+1
source

Try using reset / while / each, which is functionally equivalent to foreach according to the manual, then you can use reset in a loop like this:

<?php
$arr = array(1=>'one',2=>'two',3=>'three');
reset($arr);
$resets=0;
while (list($key, $value) = each($arr))
{
    echo "$key => $value<br />\n";
    if($value=='three')
    {
        if($resets==0){$resets++;echo "==Resetting==<br />\n";reset($arr);continue;}
    }

}

Output:

1 => one
2 => two
3 => three
== Resetting ==
1 => one
2 => two
3 => three
+1
source

Source: https://habr.com/ru/post/1529820/


All Articles