Splatpacking与array_values()一起使用数字键重新索引数组 [英] Splatpacking versus array_values() to re-index an array with numeric keys

查看:128
本文介绍了Splatpacking与array_values()一起使用数字键重新索引数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从PHP7.4开始,有一种新的可用技术用数字键重新索引数组.

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

我将其称为"阵列重新包装",或者诸如" splatpacking "之类的有趣名称.简单的过程包括使用splat运算符(...)(也称为"spread运算符")对数组进行解包,然后通过对称数组解构"将第一级元素填充到新数组中.

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

比较代码:(演示)

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

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

两者都会输出:

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

同样,splatpacking技术严格限于具有数字键的数组,因为splat运算符会阻塞其他任何事情,并且只能将解压缩后的值直接写入数组的功能仅在PHP7.4及更高版本中可用.

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?

注意,这不是关于如何为索引重新编制索引,而是array_values()与新近可用技术的比较.

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

这不同于:

  • 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.

推荐答案

重新索引第一个未设置元素的450,000个元素数组时...

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

array_values()始终是splatpacking的两倍.

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

基准脚本

示例输出:

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

在性能方面,应始终使用array_values().当函数调用技术比非函数调用技术更有效时,就是这种情况.

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.

我认为,只有当您是 CodeGolfer 时,splatpacking技术才能胜出的唯一情况是-13个字符,而5.

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

这篇关于Splatpacking与array_values()一起使用数字键重新索引数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆