I am new to PHP and am currently messing around with array_reduce
, when I see this happen:
php > echo array_reduce(array("(function($x){return $x;})"), function($p, $q) {return ($q)($p);}, "init");
Warning: Uncaught Error: Call to undefined function (function(, ){return ;})() in php shell code:1
Stack trace:
#0 [internal function]: {closure}('init', '(function(, ){r...')
#1 php shell code(1): array_reduce(Array, Object(Closure), 'init')
#2 {main}
thrown in php shell code on line 1
php > echo (function($x){return $x;})("init");
init
Essentially, there are three parts to array_reduce()
- the array, the reduce function and an initial value. Here my reduce function takes two strings func($x, $y)
and calls $y
with the argument $x
- return ($y)($x);
. So I expect that calling array_reduce(array(a1, a2, a3), ..., "init")
, it will return a1(a2(a3("init")))
as repeated function calls.
Hence, I also pass in an anonymous function (function($x){return $x;})
as a1
, hoping it will call correctly and return "init"
as the final result. Indeed when running it on its own (see the second php command), it returns "init"
correctly. However when passing into array_reduce()
, it does not work. Can someone help explain why, preferably in simple terms? And is it possible to achieve what I want?
My Answer:
php
// Array of callback functions
$callbacks = [
function($value) {
return $value * 2;
},
function($value) {
return $value + 5;
},
function($value) {
return $value / 3;
}
];
// Initial value
$initialValue = 10;
// Dynamically nest the execution of functions using array_reduce
$result = array_reduce($callbacks, function($carry, $callback) {
return $callback($carry);
}, $initialValue);
echo $result; // Output: 5
In this example, we have an array of callback functions stored in the `$callbacks` variable. We then use `array_reduce()` to dynamically nest the execution of these functions on an initial value of 10. Each callback function is applied to the result of the previous function, starting with the initial value. The final result is 5 after applying all three callback functions in sequence.
Rate this post
4 of 5 based on 4338 votesComments