开发者

convert foreach into while loop

Hi guys i need to convert a foreach loop into a while loop. Because the foreach loop does leaves the block when values have been iterated. I need the whil开发者_JS百科e loop to continue looping.

I need to iterate the items of the array but not in a foreach loop.

foreach($values as $event) {
        if($startDate >= $event['start'] && $startDate <= $event['end']  ) {
            echo '<tr><td style="background:red;">Tijd: ' . strftime("== %H:%M ==", $startDate) . '<br/></td><td>'.$startDate.'</td></tr>';
        }
        else {
            echo '<tr><td style="background:green;">Tijd: ' . strftime("== %H:%M ==", $startDate) . '<br/></td><td>'.$startDate.'</td></tr>';
        }       
    }

My last post when into a disaster srry for that.


If you simply want to iterate through the array, this should do it:

$array_length = count($values);
$iteration    = 0;

while($iteration < $array_length){
    $event = $values[$iteration];
    ...
    $iteration++;
}

This functionality is much like a for() or foreach() loop, if you only want to exit the loop when a specific condition is met, you could do it like this:

$active = true;
$iteration = 0;

while($active){
    $event = $values[$iteration];
    ...
    if(some_condition){ $active = false; }
    $iteration++;
}

Note: You should put in some code which resets the iterator or sets $active to false if the iterator grows larger than or equal to the size of the values array, or else you will run into trouble

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜