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

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

Trivial question.

Suppose I have the following code

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$words = ['Apple', 'Avocado', 'Banana', 'Blueberry'];

$dict = [];
// build a dictionary keyed on the first letter
foreach ($words as $word) {
    $letter = $word[0];
    // is this condition necessary?
    if (!isset($dict[$letter])) {
        $dict[$letter] = [];
    }
    $dict[$letter][] = $word;
}
?>

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 21: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.

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

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题