I'm trying to get counts of array values greater than n
.
I'm using array_reduce()
like so:
$arr = range(1,10);
echo array_reduce($arr, function ($a, $b) { return ($b > 5) ? ++$a : $a; });
This prints the number of elements in the array greater than the hard-coded 5
just fine.
But how can I make 5
a variable like $n
?
I've tried introducing a third argument like this:
array_reduce($arr, function ($a, $b, $n) { return ($b > $n) ? ++$a : $a; });
// ^ ^
And even
array_reduce($arr, function ($a, $b, $n) { return ($b > $n) ? ++$a : $a; }, $n);
// ^ ^ ^
None of these work. Can you tell me how I can include a variable here?
The syntax to capture parent values can be found in the
function .. use
documentation under "Example #3 Inheriting variables from the parent scope".Converting the original code, with the assistance of
use
, is then:Where
$n
is "used" from the outer lexical scope.NOTE: In the above example, a copy of the value is supplied and the variable itself is not bound. See the documentation about using a reference-to-a-variable (eg.
&$n
) to be able and re-assign to variables in the parent context.