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".
.. Inheriting variables from the parent scope [requires the 'use' form and] is not the same as using global variables .. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).
Converting the original code, with the assistance of use
, is then:
$n = 5;
array_reduce($arr, function ($a, $b) use ($n) {
return ($b > $n) ? ++$a : $a;
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With