Dev Notes

Software Development Resources by David Egan.

Reduce a Numerically Indexed Array to a Simple Array in PHP


PHP
David Egan

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

<?php
// The Array
$array = [
    ['key1' => 'val1', 'key2'=>'val2'],
    ['key3' => 'val3'],
    ['key4' => 'val4'],
    ['key5' => [
        'A' => 'foo',
        'B' => 'bar'
        ]
    ]
];

The output of var_dump($array) looks like this:

array (size=4)
  0 =>
    array (size=2)
      'key1' => string 'val1' (length=4)
      'key2' => string 'val2' (length=4)
  1 =>
    array (size=1)
      'key3' => string 'val3' (length=4)
  2 =>
    array (size=1)
      'key4' => string 'val4' (length=4)
  3 =>
    array (size=1)
      'key5' =>
        array (size=2)
          'A' => string 'foo' (length=3)
          'B' => string 'bar' (length=3)

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:

<?php
$newArray = array_merge(...$array));

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:

array (size=5)
  'key1' => string 'val1' (length=4)
  'key2' => string 'val2' (length=4)
  'key3' => string 'val3' (length=4)
  'key4' => string 'val4' (length=4)
  'key5' =>
    array (size=2)
      'A' => string 'foo' (length=3)
      'B' => string 'bar' (length=3)

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