Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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."</div>";     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>"; 
like image 255
Tapha Avatar asked May 19 '10 12:05

Tapha


People also ask

How do you end a foreach loop?

To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure.

How do you end a foreach loop in Python?

Python break statement If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.

Which is better for loop or foreach?

This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.


1 Answers

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.

like image 87
pakore Avatar answered Sep 30 '22 08:09

pakore