为什么array_values比foreach更好? [英] Why array_values is better than a foreach?
本文介绍了为什么array_values比foreach更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么 array_values()
优于foreach循环来重新索引数组?
Why array_values()
is better than a foreach loop to re-index an array?
示例1:
$arrays = [
1 => '0',
2 => '1',
3 => '2',
4 => '3',
5 => '',
6 => '',
7 => '7',
8 => [
0 => 'toto',
1 => 'manu',
2 => 'noé',
3 => 'david'
]
];
$arrayNonAssoc = [];
foreach ($arrays as $array) {
$arrayNonAssoc[] = $array;
}
因此,示例1 是不执行的错误,并且...
So the Example 1 is the error to not do and...
示例2:
$arrays = [
1 => '0',
2 => '1',
3 => '2',
4 => '3',
5 => '',
6 => '',
7 => '7',
8 => [
0 => 'toto',
1 => 'manu',
2 => 'noé',
3 => 'david'
]
];
var_dump(array_values($arrays));
我已阅读过有关此内容的信息,但未发现任何相关说明.示例1 和示例2 返回相同的结果...
I have read about it, but I didn't found any explications to this. Both Example 1 and Example 2 return the same result...
与性能有关吗?
推荐答案
- 更少的代码.
- 更容易理解的代码,因为这正是
array_values
的用途,但是您的foreach
可以做任何事情,除非您阅读并理解它. -
array_values
是在后台用C语言实现的本机PHP函数,其性能可能比自定义PHP代码高得多.
- Less code.
- Easier to understand code, because that's exactly what
array_values
is for, yet yourforeach
could do anything unless you read and understand it. array_values
is a native PHP function implemented in C behind the scenes, and likely much more performant than custom PHP code.
这篇关于为什么array_values比foreach更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文