Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created January 7, 2009 17:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kgaughan/44350 to your computer and use it in GitHub Desktop.
<?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
Copy link

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