在 PHP 中初始化(空)数组的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5966746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to initialize (empty) array in PHP
提问by Tom Auger
In certain other languages (AS3 for example), it has been noted that initializing a new array is faster if done like this var foo = []
rather than var foo = new Array()
for reasons of object creation and instantiation. I wonder whether there are any equivalences in PHP?
在某些其他语言(例如 AS3)中,已经注意到,如果这样做var foo = []
而不是var foo = new Array()
出于对象创建和实例化的原因,初始化新数组会更快。我想知道 PHP 中是否有任何等价物?
class Foo {
private $arr = array(); // is there another / better way?
}
采纳答案by Andy E
In ECMAScript implementations (for instance, ActionScript or JavaScript), Array()
is a constructor function and []
is part of the array literal grammar.?Both are optimized and executed in completely different ways, with the literal grammar not being dogged by the overhead of calling a function.
在 ECMAScript 实现(例如 ActionScript 或 JavaScript)中,Array()
是一个构造函数,[]
是数组文字语法的一部分。?两者都以完全不同的方式优化和执行,文字语法不会被调用函数的开销所困扰.
PHP, on the other hand, has language constructs that may look like functions but aren't treated as such.?Even with PHP 5.4, which supports []
as an alternative, there is no difference in overhead because, as far as the compiler/parser is concerned, they are completely synonymous.
另一方面,PHP 具有可能看起来像函数但不被视为函数的语言结构。?即使使用 PHP 5.4,它支持[]
作为替代方案,开销也没有区别,因为就编译器/解析器而言就其而言,它们完全是同义词。
// Before 5.4, you could only write
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// As of PHP 5.4, the following is synonymous with the above
$array = [
"foo" => "bar",
"bar" => "foo",
];
If you need to support older versions of PHP, use the former syntax.?There's also an argument for readability but, being a long-time JS developer, the latter seems rather natural to me.? I actually made the mistake of trying to initialise arrays using []
when I was first learning PHP.
?[]
当我第一次学习 PHP 时,我实际上犯了尝试初始化数组的错误。
This changeto the language was originally proposed and rejected due to a majority vote against by core developers with the following reason:
由于核心开发人员的多数票反对,最初提出并拒绝了对语言的这种更改,原因如下:
This patch will not be accepted because slight majority of the core developers voted against. Though if you take a accumulated mean between core developers and userland votes seems to show the opposite it would be irresponsible to submit a patch witch is not supported or maintained in the long run.
这个补丁不会被接受,因为核心开发者的微弱多数投了反对票。但是,如果您在核心开发人员和用户投票之间采取累积平均值似乎表明相反,提交补丁从长远来看不受支持或维护是不负责任的。
However, it appears there was a change of heart leading up to 5.4, perhaps influenced by the implementations of support for popular databases like MongoDB (which use ECMAScript syntax).
然而,似乎在 5.4 之前发生了改变,这可能是受到了对流行数据库(如 MongoDB(使用 ECMAScript 语法)的支持)的实现的影响。
回答by C Landreaux
$myArray = [];
Creates empty array.
创建空数组。
You can push values onto the array later, like so:
您可以稍后将值推送到数组中,如下所示:
$myArray[] = "tree";
$myArray[] = "house";
$myArray[] = "dog";
At this point, $myArray contains "tree", "house" and "dog". Each of the above commands appends to the array, preserving the items that were already there.
此时,$myArray 包含“tree”、“house”和“dog”。上述每个命令都附加到数组中,保留已经存在的项目。
Having come from other languages, this way of appending to an array seemed strange to me. I expected to have to do something like $myArray += "dog" or something... or maybe an "add()" method like Visual Basic collections have. But this direct append syntax certainly is short and convenient.
来自其他语言,这种附加到数组的方式对我来说似乎很奇怪。我希望必须做一些类似 $myArray += "dog" 之类的事情……或者像 Visual Basic 集合那样的“add()”方法。但是这种直接追加的语法确实简短而方便。
You actually have to use the unset() function to remove items:
您实际上必须使用 unset() 函数来删除项目:
unset($myArray[1]);
... would remove "house" from the array (arrays are zero-based).
...将从数组中删除“房子”(数组从零开始)。
unset($myArray);
... would destroy the entire array.
...会破坏整个阵列。
To be clear, the empty square brackets syntax for appending to an array is simply a way of telling PHP to assign the indexes to each value automatically, rather than YOU assigning the indexes. Under the covers, PHP is actually doing this:
需要明确的是,用于附加到数组的空方括号语法只是告诉 PHP 自动为每个值分配索引的一种方式,而不是您分配索引。在幕后,PHP 实际上是这样做的:
$myArray[0] = "tree";
$myArray[1] = "house";
$myArray[2] = "dog";
You can assign indexes yourself if you want, and you can use any numbers you want. You can also assign index numbers to some items and not others. If you do that, PHP will fill in the missing index numbers, incrementing from the largest index number assigned as it goes.
如果需要,您可以自己分配索引,并且可以使用任何您想要的数字。您还可以为某些项目而不是其他项目分配索引号。如果这样做,PHP 将填充缺失的索引号,从分配的最大索引号开始递增。
So if you do this:
所以如果你这样做:
$myArray[10] = "tree";
$myArray[20] = "house";
$myArray[] = "dog";
... the item "dog" will be given an index number of 21. PHP does not do intelligent pattern matching for incremental index assignment, so it won't know that you might have wanted it to assign an index of 30 to "dog". You can use other functions to specify the increment pattern for an array. I won't go into that here, but its all in the PHP docs.
...项目“dog”的索引号为 21。PHP 不会为增量索引分配进行智能模式匹配,因此它不会知道您可能希望它为“dog”分配 30 的索引”。您可以使用其他函数来指定数组的增量模式。我不会在这里讨论这个,但它都在 PHP 文档中。
Cheers,
干杯,
-=Cameron
-=卡梅伦
回答by Md. Shafiqur Rahman
Prior to PHP 5.4:
在 PHP 5.4 之前:
$myArray = array();
PHP 5.4 and higher
PHP 5.4 及更高版本
$myArray = [];
回答by Adrian
In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.
在 PHP 中,数组就是数组;没有原始与对象的考虑,因此没有可比的优化。
回答by James C
What you're doing is 100% correct.
你在做什么是100%正确的。
In terms of nice naming it's often done that private/protected properties are preceded with an underscore to make it obvious that they're not public. E.g. private $_arr = array()
or public $arr = array()
就好的命名而言,通常会在私有/受保护的属性前面加上下划线,以明确它们不是公共的。例如private $_arr = array()
或public $arr = array()
回答by Pyetro
Try this:
尝试这个:
$arr = (array) null;
var_dump($arr);
// will print
// array(0) { }
回答by improgrammer
Initializing a simple array :
初始化一个简单的数组:
<?php $array1=array(10,20,30,40,50); ?>
Initializing array within array :
在数组中初始化数组:
<?php $array2=array(6,"santosh","rahul",array("x","y","z")); ?>
Source : Sorce for the code
来源:代码来源
回答by Matthieu Napoli
There is no other way, so this is the best.
有没有别的办法,所以这是最好的。
Edit: This answer is not valid since PHP 5.4 and higher.
编辑:此答案自 PHP 5.4 及更高版本起无效。