/**
* all in collection?
*
* Passes each element of the collection to the given function. The method
* returns true if the function never returns false or null.
*
* If the function is not given, an implicit
* function ($v) { return ($v !== null && $v !== false) is added
* (that is all() will return true only if none of the collection members are false or null.)
*
* @param array $arr input array
* @param function $lambda takes an element, returns a bool (optional)
* @return boolean
*/
function all($arr, $lambda=null) {
// these differ from PHP's "falsy" values
if (!is_callable($lambda)) {
foreach ($arr as $value)
if ($value === false || $value === null)
return false;
} else {
foreach ($arr as $value)
if (!call_user_func($lambda, $value))
return false;
}
return true;
}
你可以这样称呼它:
var_dump(all($array, 'is_numeric'));
var_dump(all($array, 'is_string'));
var_dump(all($array, function($x) { return $x != 'fun';})); // PHP >= 5.3.0