How do I include a variable inside a callback function?

I am trying to get the number of array values ​​greater than n

.

I am using array_reduce()

like this:

$arr = range(1,10);
echo array_reduce($arr, function ($a, $b) { return ($b > 5) ? ++$a : $a; });

      

That being said, the number of elements in the array is greater than the hard-coded one 5

just fine.

But how can I make a 5

variable of type $n

?

I've tried representing the 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 works. Can you tell me how to include a variable here?

+3


source to share


1 answer


The syntax for writing parent values ​​can be found in the documentation function .. use

under Example # 3 Inheriting Variables from the Parent Scope.

.. Inheriting variables from the parent scope [use form is required and] is not the same as using global variables. The parent scope of the closure is the function in which the closure was declared (not necessarily the function it was called).

Converting source code with use

:



$n = 5;
array_reduce($arr, function ($a, $b) use ($n) {
    return ($b > $n) ? ++$a : $a;
});

      

Where is $n

"used" from the outer lexical scope.

NOTE. The above example provides a copy of the value and the variable itself is not bound. See the documentation on using variable-reference (for example &$n

) to be able to and overwrite variables in the parent context.

+11


source







All Articles