I’m writing a function named all to check all elements inside an array $arr, returning a single boolean value (based of $f return value). This is working fine passing custom functions (see the code with $gte0 been passed to all).
However sometimes one want just check that an array contains all true values: all(true, $arr) will not work becase true is passed as boolean (and true is not a function name). Does PHP have a native true() like function?
function all($f, array $arr)
{
return empty($arr) ? false : array_reduce($arr, function($v1, $v2) use ($f) {
return $f($v1) && $f($v2);
}, true);
}
$test = array(1, 6, 2);
$gte0 = function($v) { return $v >= 0; }
var_dump(all($gte0, $test)); // True
$test = array(true, true, false);
$id = function($v) { return $v; } // <-- this is what i would avoid
var_dump(all($id, $test)); // False
all(true, $test); // NOT WORKING because true is passed as boolean
all('true', $test); // NOT WORKING because true is not a function
EDIT: another way could be checking $f in all function:
$f = is_bool($f) ? ($f ? function($v) { return $v; }
: function($v) { return !$v; } ): $f;
After adding this, calling all with true is perfectly fine.
intvalmight do what you’re looking for (especially as the array only contains integers in your example):However, many types to integer conversions are undefined in PHP and with float this will round towards zero, so this might not be what you want.
The more correct “function” would be the opposite of boolean true:
empty, but it’s not a function, so you can’t use it (and invert the return value):And there is no function called
boolvalor similar in PHP, so write it yourself if you need it 😉Additionally your
allfunction could be optimized. While iterating, if the current result is alreadyFALSE, the end result will always beFALSE. And no need to call$f()n * 2times anyway:Edit: knittl is right pointing to
array_filter, it converts to boolean with no function given which seems cool as there is no “boolval” function:Making the first function parameter optional will do you a proper bool cast on each array element thanks to
array_filter.