Good question! Okay, let's clean this up a bit:
function array_pluck($key, $array)
{
return array_map(function ($item) use ($key) {
return $item[$key];
}, $array);
}
It's a bit easier to understand this way.
First, the goal of this function is to return a one-dimensional array of the values of a specific key from a multidimensional array. Here are examples:
$testArray = array(
array("xxx" => "hello", "yyy" => "goodbye"),
array("xxx" => "hi", "yyy" => "bye"),
array("xxx" => "hey", "yyy" => "peace"),
);
php > var_dump(array_pluck('xxx', $testArray));
array(3) {
[0]=>
string(5) "hello"
[1]=>
string(2) "hi"
[2]=>
string(3) "hey"
}
php > var_dump(array_pluck('yyy', $testArray));
array(3) {
[0]=>
string(7) "goodbye"
[1]=>
string(3) "bye"
[2]=>
string(5) "peace"
}
php >
As you can see, this is returning $testArray[<index>]['xxx']
and $testArray[<index>]['yyy']
respectively, for each array inside the parent array.
Now to explain what's going on with the return
. The array_map()
function takes a function (or "Callable") as the first parameter, and an array as the second parameter. The function is run for each element in the array, and then array_map()
adds the return value of that function to the new array that array_map()
returns.
This is called an anonymous function:
function ($item) use ($key) {
return $item[$key];
}
It is just like any other function, except it doesn't have a name, and it does have the use (...)
syntax. The use ($key)
means to "import" $key
from the outer function (array_pluck()
), so it can be used inside this anonymous function. Each element of $testArray
in the example above, gets passed to this anonymous function as $item
. When return $item[$key]
occurs, only the anonymous function returns (exits), and the array_map()
continues on to the next element.