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

坚强是说给别人听的谎言 提交于 2019-12-10 00:34:49

问题


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 fills a new array with with the contents.

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.


回答1:


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

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, you should always use array_values(). This is one case when a function-calling technique is more efficient than a non-function-calling technique.


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



来源:https://stackoverflow.com/questions/57725811/splatpacking-versus-array-values-to-re-index-an-array-with-numeric-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!