PHP Quoting through a Half Array

So I have an array like this:

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

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

+3
source share
9 answers

Works for any array, not just for numeric keys 0, 1, ...:

$i = 0;
foreach ($obj as $element) {
    // do something
    if (++$i == 50) {
        break;
    }
}
+7
source

Clean way:

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

The usual way (this will only work for arrays with numerical indices and in ascending order):

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

Or, if you want to use foreach, you can have a use counter:

$counter = 0;
foreach($obj as $element){
  if( $counter == 50) break;
  // my eyes!!! this looks bad!
  $counter++;
}
+11
source

.

for($i=0; $i<count($obj)/2; $i++)
{
  $element = $obj[$i];
  // do something
}

, 50

$c = min(count($obj), 50);
for($i=0; $i<$c; $i++)
{
  $element = $obj[$i];
  // do something
}
+10

SPL iterators, :

$limit = new LimitIterator(new ArrayIterator($obj), 0, 50);
foreach ($limit as $element) {
    // ...
}

, . array_slice.

+3
for ($i = 0, $el = reset($obj); $i < count($obj)/2; $i++, $el = next($obj)) {
    //$el contains the element
}
+1

$filtered = array_slice($array,0,((count($array)/2) < 50 && count($array) > 50 ? 50 : count($array)));
//IF array/2 is les that 50- while the array is greater then 50 then split the array to 50 else use all the values of the array as there less then 50 so it will not devide
foreach($filtered as $key => $row)
{
  // I beliave in a thing called love.
}

What's going on here

array_slice(
  $array, //Input the whole array
  0, //Start at the first index
  (
    count($array)/2 //and cut it down to half
  )
)
+1
source
for($i=0; $i < 50; $i++)
{
  // work on $obj[$i];
}
0
source

Here is the most obvious approach to me:

$i = 0;          // Define iterator

while($obj[$i])  // Loop until there are no more
{
 trace($obj[$i]); // Do your action
 $i++;           // Increment iterator
}
0
source

This should work in all cases for half the array, regardless of length and whether it has numeric indices or not:

$c = intval(count($array)/2);
reset($array);
foreach(range(1, $c) as $num){
    print key($array)." => ".current($array)."\n";
    next($array);
}
0
source

Source: https://habr.com/ru/post/1752690/


All Articles