doulei2100 2018-02-01 13:27
浏览 54
已采纳

是否有必要在追加数组之前定义它?

Trivial question.

Suppose I have the following code

  1. <?php
  2. error_reporting(E_ALL);
  3. ini_set('display_errors', 1);
  4. $words = ['Apple', 'Avocado', 'Banana', 'Blueberry'];
  5. $dict = [];
  6. // build a dictionary keyed on the first letter
  7. foreach ($words as $word) {
  8. $letter = $word[0];
  9. // is this condition necessary?
  10. if (!isset($dict[$letter])) {
  11. $dict[$letter] = [];
  12. }
  13. $dict[$letter][] = $word;
  14. }
  15. ?>

Usually when I build a dictionary, before appending an entry, I ensure that the array exist as shown in my example.

I always thought a warning would show up otherwise, however it does not seem to be the case.

So is the IF condition necessary?

  • 写回答

1条回答 默认 最新

  • doulou0882 2018-02-01 13:41
    关注

    From the official documentation on arrays (emphasis mine):

    $arr[key] = value;

    $arr[] = value;

    // key may be an integer or string

    // value may be any value of any type

    If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment.

    No warning will be produced, but for clarity's sake it is preferred to initialize by direct assignment as you've always been doing.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部