开发者

How would I stop this foreach loop after 3 iterations? [duplicate]

开发者 https://www.devze.com 2022-12-31 12:47 出处:网络
This question already has answers here: Can you 'exit' a loop in PHP? (6 answers) Closed 3 years ago.
This question already has answers here: Can you 'exit' a loop in PHP? (6 answers) Closed 3 years ago.

Here is the loop.

foreach($results->results as $result){
    echo '<div id="twitter_status">';
    echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
    $text_n = $result->text; 
    echo "<div id='text_twit'>".$text_n."</d开发者_运维问答iv>";
    echo '<div id="twitter_small">';
    echo "<span id='link_user'".'<a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a></span>';
    $date = $result->created_at;

    $dateFormat = new DateIntervalFormat();

    $time = strtotime($result->created_at);

    echo "<div class='time'>";

    print sprintf('Submitted %s ago',  $dateFormat->getInterval($time));

    echo '</div>';

    echo "</div>";
    echo "</div>";


With the break command.

You are missing a bracket though.

$i=0;
foreach($results->results as $result){
//whatever you want to do here

$i++;
if($i==3) break;
}

More info about the break command at: http://php.net/manual/en/control-structures.break.php

Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)

The code would be:

for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}

It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.


  • Declare a variable before the loop, initialize to 0.
  • Increment variable at the beginning of the body of for-each.
  • Check variable at the end of the body of for-each.
    • If it's 3, break.

You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.


Increment some counter $i at the beggining of the loop and break; when it reaches 3, e.g.:

if ($i++ == 3)
    break;


foreach($results->results as $i => $result){ 
   if($i==3) break; 
   //whatever you want to do here 
}
0

精彩评论

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