Reduce a Numerically Indexed Array to a Simple Array in PHP
PHP
Reducing a numerically indexed multi-dimensional array to a simple array can be achieved easily by means of combining array_merge()
with the ‘splat’ (...
) operator.
This uses the concept of argument unpacking. It can be really useful if you are starting with a numerically indexed array of arrays and you need to combine them into a single simple array of key-value pairs.
Starting Point
The output of var_dump($array)
looks like this:
Operation
Assuming that you’re using PHP version 5.6 and upwwards (and you should be), you can run the array through array_merge()
using the ‘splat’ operator:
As I understand it (please correct me via a comment if I have this wrong):
array_merge()
accepts an initial array along with a variable list of arrays to merge.- Using the ‘splat’ operator tells PHP to unpack the input array into variables.
- In our case, these variables are arrays, because the staring point was an array of arrays - so we’re passing multiple arrays into
array_merge()
for processing. - Because each variable is a singular array, they’re no longer numerically indexed.
array_merge()
will merge the multiple arrays, and the output array is as associative array, indexed by the keys.
Result
The output of array_merge(...$array));
looks like this:
Aside: Why Splat?
I don’t know if unpacking arguments is technically an “operation”, so ...
may not really be an operator, and it doesn’t look like something that’s gone splat. I’ve read that the symbol for this is in Ruby “*”, and this is where the term originated.
References
comments powered by Disqus