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".
- RFC: Spread Operator in Array Expression
- The spread operator became available in PHP5.6
- Symmetric Array Destructuring became available in PHP7.1
- Laravel News: Spread Operator for Arrays Coming to PHP 7.4
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:
- Re-index numeric array keys
- How do you reindex an array in PHP?
- PHP reindex array? [duplicate]
- array_unique and then renumbering keys [duplicate]
and the other tens of old pages that ask how to reindex an array.