Combining Parallel Arrays (in PHP)

I was today years old when I discovered you can pass multiple arrays to PHP’s array_map() function. 😶
For example, lets say you have two parallel arrays: $firstNames and $lastNames.
You can use array_map() to combine them into a single array of $fullNames. Here’s how:
$firstNames = [“Alice”, “Bob”, “Clarence”];$lastNames = [“Albinia”, “Barker”, “Cannon”];
$fullNames = array_map(function () { return “$firstName $lastName”;}, $firstNames, $lastNames);
As a bonus, you can also pass additional variables with “use”:
$intro = “Hello, my name is”;$greetings = array_map(function ($firstName, $lastName) use ($intro){ return “$intro $firstName $lastName”;}, $firstNames, $lastNames);
// Hello, my name is Alice Albinia// Hello, my name is Bob Barker// Hello, my name is Clarence Cannon
Need indexes? Our array_map() function can also be implemented to work like a for loop by passing array_keys() as the last argument:
$greetings = array_map(function ($firstName, $lastName, $i) use ($intro){ return “($i) $intro $firstName $lastName”;}, $firstNames, $lastNames, array_keys($firstNames));
// (1) Hello, my name is Alice Albinia// (2) Hello, my name is Bob Barker// (3) Hello, my name is Clarence Cannon
Hope someone finds this useful! I just found it funny how I use this function almost daily and never realized it took multiple arguments. 😎