Skip to content

Instantly share code, notes, and snippets.

@monecchi
Last active June 7, 2016 02:54
Show Gist options
  • Save monecchi/05b0533e42be4b41fb48a5701763c1ca to your computer and use it in GitHub Desktop.
Save monecchi/05b0533e42be4b41fb48a5701763c1ca to your computer and use it in GitHub Desktop.
Receive one array as input, filter values from it, and output as a new array.
// Receive one array as input, filter values from it, and output as another array.
// The function should loop through up to x iterations.
// Credits go to the author of the answer here: http://stackoverflow.com/a/7274450/1152876
*/
* Exit the foreach loop when count is reached.
* Use a foreach to iterate over the full array, and if the stated maximum count isn't reached, process the whole array.
* Otherwise, if the maximum iteration is reached, jump out of the loop.
*/
<?php
$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;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment