Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 567
Joe W Avatar asked Sep 01 '11 17:09

Joe W


1 Answers

$max_iterations = 100;

for ($i=1;$i <=$max_iterations;$i++)
{
    if ($i <= count($array))
        //do what u need
    else
        break;      
}
like image 75
xbonez Avatar answered Sep 29 '22 14:09

xbonez