Alex Rivera | Logout

Perform PHP loops until end of array OR reaches certain number of iterations?

Asked 2011-09-01T17:54:33.693
12

I wish to receive one array as input, filter values from it, and output as another array. The function should loop through up to x iterations.

For example, if I wanted to output all the values from the input, I would use:

<?php
$i=0;
foreach ($array as $data) {
    if ($data['type'] != 'some_value') {
        $formatted_array[$i] = $data;
        $i++;
    }
}
return $formatted_array;    

But if $array had a large index, the $formatted_array would be larger than I need. I tried using a for loop with multiple conditions, but it seems to get stuck in an infinite loop.

I'm not a developer by trade, so the logic is difficult to comprehend. I'm not getting errors, so it's hard to understand where exactly I'm going wrong.

How can I perform PHP loops until end of array or until the function reaches certain number of iterations?

Edit
Report

1 Answer

15

You're on the right track - you can exit the foreach loop when you reach your count. You use a foreach to iterate over the full array and if you never reach your stated maximum count, you will process the whole array. But if you do reach the maximum, jump out of the loop.

$i = 0;
// Don't allow more than 5 if the array is bigger than 5
$maxiterations = 5;
foreach ($array as $data) {
  if ($i < $maxiterations) {
    if ($data['type'] != 'some_value') {
        $formatted_array[$i] = $data;
        $i++;
    }
  }
  else  {  // Jump out of the loop if we hit the maximum
     break;
  }
}
return $formatted_array; 
answered 2011-09-01T17:59:07.880

Your Answer