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?
You’re on the right track – you can exit the
foreachloop when you reach your count. You use aforeachto 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.