Create a gist now

Instantly share code, notes, and snippets.

<?php
/*
* Two annoying omissions from PHP are the lack of array_all() and array_any(), which check if
* a condition represented by a callback holds for all or any of the elements in an array.
*/
function array_all(array $arr, $cb) {
foreach ($arr as $e) {
if (!call_user_func($cb, $e)) {
return false;
}
return true;
}
}
function array_any(array $arr, $cb) {
foreach ($arr as $e) {
if (call_user_func($cb, $e)) {
return true;
}
return false;
}
}
@mmarinero

Hi, I guess this was written on a hurry and forgotten. It only checks the first element of the array and immediately returns.
Since it's easy to find Googling, this is a correct version.

/*
 * Two annoying omissions from PHP are the lack of array_all() and array_any(), which check if
 * a condition represented by a callback holds for all or any of the elements in an array.
 */
function array_all($array, $callback) {
    foreach ($array as $val) {
        if (!$callback($val)) {
            return false;
        }
    }
    return true;
}

function array_any($array, $callback) {
    foreach ($array as $val) {
        if ($callback($val)) {
            return true;
        }
    }
    return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment