Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Looping through half the array

Tags:

arrays

loops

php

So I have an array like this:

foreach($obj as $element){
//do something
}

But If the array contains more than 50 elements (it is usually 100) I only want to loop through the first 50 of them, and then break the loop.

like image 604
Matt Elhotiby Avatar asked Nov 27 '22 01:11

Matt Elhotiby


1 Answers

Clean way:

$arr50 = array_slice($obj, 0, 50);
foreach($arr50 as $element){
    // $element....
}

Normal way (this will work only for arrays with numeric indexes and with asc order):

for($i=0; $i<50 && $i<count($obj); $i++){
  $element = $obj[$i];
}

Or if you want to use foreach you will have to use a counter:

$counter = 0;
foreach($obj as $element){
  if( $counter == 50) break;
  // my eyes!!! this looks bad!
  $counter++;
}
like image 197
Cristian Avatar answered Dec 05 '22 23:12

Cristian