0

from documentation, in simple terms I have inferred that array_reduce takes an array as first parameter, processes according to the function defined in second argument, and iterates over the result, till all the values of the first parameter array are exhausted.

But particularly in this example, it takes the array returned from getActiveWidgets(). Till here ok, What is use statement?

$widgets = array_reduce(
            ThemeActiveWidgets::getActiveWidgets(),
            function ($carry, $item) use($model) {
                if ($item['part_id'] === $model['id']) {
                    $carry[]=$item;
                }
                return $carry;
            },
            []
        );
Ramesh Pareek
  • 1,601
  • 3
  • 30
  • 55
  • use statement...? – clearshot66 Sep 06 '17 at 18:22
  • `use` just makes `$model` available inside of the function body. You wouldn't be able to access it otherwise. – mpen Sep 06 '17 at 18:25
  • The use statements takes a variable and injects it into the function's scope. – aynber Sep 06 '17 at 18:25
  • http://php.net/manual/en/functions.anonymous.php : `Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. From PHP 7.1, these variables must not include superglobals, $this, or variables with the same name as a parameter.` – aynber Sep 06 '17 at 18:26
  • ok@aynber, Is it same as to wrap array_reduce in another function and supply $model as an argument? – Ramesh Pareek Sep 08 '17 at 12:14

1 Answers1

2

I'll break it down a little bit for you.

The function array_reduce() takes in two parameters, the first one being an array, and the second being a function, which in this case is a closure, or anonymous function.

In your code, you are getting an array by calling ThemeActiveWidgets::getActiveWidgets() and passing it as the first parameter to array_reduce(). As a second parameter, you are passing a function, like so:

function ($carry, $item) use($model) { ... }

Since this IS an anonymous function, the variable $model (wherever you defined it), is out of the scope of this anonymous function, which in simpler words means that you cannot access that $model variable within the anonymous function. However, YOU CAN access it if you "pass it" in to the function's scope by using use($model) in the function declaration.

In regards to the if statement if ($item['part_id'] === $model['id']), you are just accessing the second argument of your anonymous function, and comparing the value that the index ['part_id'] holds to the value that the $model['id'] (also an array) holds.

I hope this explanation helps!

idelara
  • 1,786
  • 4
  • 24
  • 48