开发者

perform change code in a foreach halfway through iterations

I am trying to create a php foreach statement that outputs different code for the first 5 iterations, and then does a different output f开发者_开发问答or the rest.

I found this snippet, which does a break at a given limit, but how could I continue from the last iteration on another foreach loop? That's probably not the best way to do it anyways.

 $i = 0;
foreach ($arr as $k => $v) {
    /* Do stuff */
    if (++$i == 2) break;
}

Is this possible? How would I go about it?

Thanks! Zeem


You can use array_slice for this:

foreach (array_slice($arr, 0, 5, true) as $k => $v) {
    /* Do stuff 1-5 */
}
foreach (array_slice($arr, 5, null, true) as $k => $v) {
    /* Do stuff 6-end */
}


Are you look for something like...?

$i = 0;
foreach ($var as $k => $v) {
    if ($i < 5) {
        // do something here for the first five iterations
    }
    else {
        // do something else here for further iterations
    }
    $i++;
}


$i = 0;
foreach ($arr as $k => $v) {
    if ($i < 5) { 
        /* do stuff */
    } else { 
        /* other stuff */
    }
    $i++;
}


I'm making the assumption your array isn't associative, and thereforce $k will be the numeric index. If not the case you'll need your $i.

foreach ($arr as $k => $v) {
    if ($k < 5) {
        Do stuff
    } else {
        Do other stuff
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜