duansai1314 2015-08-20 01:31
浏览 51
已采纳

最好的方法是在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']";

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?

  • 写回答

2条回答 默认 最新

  • drjk87189 2015-08-20 01:37
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示