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.
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++;
}
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