1

I'm quite new to PHP. How can I change this foreach loop to only loop twice?

<?php 

foreach($results as $row):

?>
3
  • You need a counter variable, which you can simply increment and check if it is equals to 2, if yes break the loop. Commented Apr 22, 2016 at 11:34
  • 1
    Then use for loop for that Commented Apr 22, 2016 at 11:34
  • Do please give it some though / Give it a try yourself, nothing will explode if you try, and it's the best way to learn. Commented Apr 22, 2016 at 11:35

3 Answers 3

2

Try this code, you just need a counter variable, initialize your counter variable from zero and increment it after each iteration.

<?php 
    $counter = 0; 
    foreach($results as $row) {
         //your code
         if($counter == 1)
         {
              break;
         }
         $counter++;   
    }

    ?>
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome @jord49 :)
0

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
}
?>

Comments

0
<?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.

Comments

Your Answer

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.

Ask question

Explore related questions

See similar questions with these tags.