user3367927
user3367927

Reputation:

forloop continue again after end of the iteration

I used function with same logic given below Given below code is sample of same logic i used, i need to continue the for loop after end of the iteration, i assign 0 to the variable $j at end so forloop need to continue, why its closed the process.

for($i=$j;$i<7;$i++){

echo "<br/>".$i;
if($i == 6){$j=0;continue;}
}

Actual Output

1
2
3
4
5
6 

Expected output

1
2
3
4
5
6 
1
2
3
4
5
6 
.....etc

My Original code sample is

 foreach($Qry_Rst as $key=>$Rst_Val){
   for($j=$ItrDt;$j<7;$j++){
     $ItrDate =  date('Y-m-d', mktime(0, 0, 0, $month, $day + $j, $year));
                if($ItrDate == $Rst_Val['sloat_day']){
                  $TimeTableAry[$loop_itr] = $Rst_Val;
                   break
                 }
   }
}

Upvotes: 0

Views: 39

Answers (2)

kero
kero

Reputation: 10638

The doc says

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

So instead of $j just use $i to reset the loop. As this (demo)

$j = 1;
$current = 0;
for ($i=$j; $i<4; $i++) {
    printf("i: %d, j: %d\n", $i, $j);
    if ($i==3 && $current < 5) {
        $i = -1;
        $j = mt_rand(0,3);
        $current++;
        continue;
    }
}

shows, you actually need to reset $i = -1; so it will be 0 after $i++ will be evaluated.


But with this you'll have an if in every iteration of the loop although you only need it for one. Basically you don't need it for the iteration itself but only to start a next one, so there must be something else here.

function doFor($data, $callback) {
    $dataLength = count($data);
    for ($i=0; $i<$dataLength; $i++) {
        call_user_func($callback, $data[$i]);
    }
    return $data;
}

Isolating the loop into its own function will allow for one line that will execute the wanted callback allowing your main code to be something like (demo)

$data = array(array("foo","bar"),array("hello"),array("world","!"));

function justDump($obj) {
    var_dump($obj);
};

$i = 0;
do {
    $data = doFor($data, 'justDump');
    print "<br>";
    $i++;
} while($i<5);

Upvotes: 2

CrazySabbath
CrazySabbath

Reputation: 1334

You can also try the way you originally wanted (only slightly edited):

//counter to avoid infinite loop
$counter = 0;
for($i=$i;$i<7;$i++){
    echo "<br/>".$i;
    if($i == 6){
        $i=0; 
        $counter++; 
        continue;
    }
    if($counter == 5){break;}
}

1
2
3
4
5
6
1
2
3
...

Upvotes: 0

Related Questions