best way append named array to array in PHP 5.2

杀马特。学长 韩版系。学妹 提交于 2019-12-11 11:55:08

问题


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']";

Now I learned that the [] notation for arrays does not work in older versions of PHP, like PHP 5.2.

Instead I have to do;

$array = array(
  "error" => array()
);

array_push($array["error"], "new error message as element 0 of $array['error']");

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.

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?


回答1:


EDIT: The first code snippet in the original post was reading $array = array[];. The author corrected it after I posted this answer.


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']";

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.




回答2:


The first way of creating array in PHP is incorrect. This syntax works in PHP5.2 below too, so you dont need to worry about it. You don't need to use array_push and simply do following.

The correct syntax is:

$array = array(); // notice it doesn't to array[]

// add error when there is one
$array["error"][] = "new error message as element 0 of $array['error']";


来源:https://stackoverflow.com/questions/32108173/best-way-append-named-array-to-array-in-php-5-2

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