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>";
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.
Python break statement If the break statement is inside a nested loop (loop inside another loop), the break statement will terminate the innermost loop.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With