Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I'm quite new to PHP. How can I change this foreach loop to only loop twice?
<?php foreach($results as $row): ?>
Try this code, you just need a counter variable, initialize your counter variable from zero and increment it after each iteration.
zero
<?php $counter = 0; foreach($results as $row) { //your code if($counter == 1) { break; } $counter++; } ?>
Add a comment
You could iterate up to the size of the array or 2 - the smaller of the two.
<?php $maxInd = min(2, count($results); for ($i = 0; $i < $maxInd; ++$i) { $row = $results[$i]; // Do something interesting with $row } ?>
<?php for ($i = 0, $count = count($results); $i < $count; ++$i) { var_dump($results[$i]); // or assign it to $result variable $result = $results[$i]; } ?>
But this will work only for collection there are some examples for example generators where you must use foreach.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.