phparraysreindexargument-unpackingphp-7.4

Splatpacking versus array_values() to re-index an array with numeric keys


As of PHP7.4, there is a newly available technique to re-index an array with numeric keys.

I'll call it "array re-packing" or maybe something fun like "splatpacking". The simple process involves using the splat operator (...) -- aka "spread operator" -- to unpack an array then filling a new array with the first-level elements via "symmetric array destructuring".

Comparison Code: (Demo)

$array = [2 => 4, 5 => 3, "3" => null, -10.9 => 'foo'];

var_export(array_values($array));
var_export([...$array]);

Both will output:

array (
  0 => 4,
  1 => 3,
  2 => NULL,
  3 => 'foo',
)

Again, the splatpacking technique is strictly limited to arrays with numeric keys because the splat operator chokes on anything else AND the ability to write the unpacked values directly into an array is only available from PHP7.4 and higher.

With the two techinques delivering the same output in qualifying situations, when should I use one over the other?

Note, this is not about how to reindex keys, but a comparison of array_values() versus a newly available technique.

This is different from:

and the other tens of old pages that ask how to reindex an array.


Solution

  • When re-indexing a 450,000 element array which has its first element unset...

    Before PHP8.3, array_values() is consistently twice as fast as splatpacking.

    $array = range(0, 450000);
    unset($array[0]);
    

    Benchmark script

    Sample output:

    Duration of array_values: 15.328378677368
    Duration of splat-pack: 29.623107910156
    

    In terms of performance, before PHP8.3 you should always use array_values(). This is one case when a function-calling technique is more efficient than a non-function-calling technique.

    As of PHP8.3 (proven by my old benchmarking script), the performance difference between the two techniques has become negligible (no longer a concern).


    I suppose the only scenario where the splatpacking technique wins is if you are a CodeGolfer -- 13 characters versus 5.