在PHP 5.2中将命名数组追加到数组的最佳方法 [英] best way append named array to array in PHP 5.2
问题描述
我习惯了这种表示法,用于创建空数组,并在需要时向其中添加命名元素;
I got used to this notation for creating empty arrays and add named elements to them when needed;
$array = [];
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
现在我了解到,数组的[]表示法在旧版本的PHP(例如PHP 5.2)中不起作用.
Now I learned that the [] notation for arrays does not work in older versions of PHP, like PHP 5.2.
相反,我必须做;
$array = array(
"error" => array()
);
array_push($array["error"], "new error message as element 0 of $array['error']");
在我的情况下,这种方式有点不方便,因为关于第一个代码段的妙处是,仅当发生实际错误时,才会在 $ array
中创建错误"条目,而在后一种情况下,该条目(尽管为空)以任何一种方式存在.
This way is a little bit inconvenient in my case because the great thing about the first code snippet is that the "error" entry in $array
is only created when there is an actual error, whereas in the latter case the entry (although empty) exists either way.
是否有一种方法可以以类似的功能"(即在需要时指定/添加命名元素,而不是在初始化时添加),并且在PHP 5.2中也易于理解?
Is there a way to get similar 'functionality' (i.e. specifying/adding named elements when needed, not at initialisation) in a way that is also easily readable in PHP 5.2?
推荐答案
原始文章中的第一个代码段是读取 $ array = array [];
.我发布此答案后,作者对此进行了纠正.
The first code snippet in the original post was reading $array = array[];
. The author corrected it after I posted this answer.
第一个被截断的代码不正确.没有 array []
这样的东西.正确的语法是 array()
.
The first code snipped is incorrect. There is no such thing as array[]
. The correct syntax is array()
.
$array = array();
// in case there is an error
$array["error"][] = "new error message as element 0 of $array['error']";
您不必担心PHP版本.自从PHP诞生以来,这种语法就一直在PHP上起作用,并且可能永远有效.继续使用它.
You don't have to worry about PHP versions. This syntax always worked on PHP since its dawn and it will probably work forever. Keep using it.
这篇关于在PHP 5.2中将命名数组追加到数组的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!