【问题标题】:Is it necessary to define the array before appending to it?是否有必要在追加之前定义数组?
【发布时间】:2018-07-12 07:46:27
【问题描述】:

小问题。

假设我有以下代码

<?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;
}
?>

通常当我构建字典时,在添加条目之前,我会确保数组存在,如我的示例所示。

我一直认为否则会出现警告,但似乎并非如此。

那么 IF 条件是必要的吗?

【问题讨论】:

  • 好吧,如果它已经设置它会被覆盖,但除此之外没有必要。
  • If 不是必需的。

标签: php multidimensional-array append isset


【解决方案1】:

来自official documentation on arrays(强调我的):

$arr[key] = value;

$arr[] = value;

// key may be an integer or string

// value may be any value of any type

如果$arr还不存在,就会被创建,所以这也是一个 创建数组的另一种方法。然而这种做法 不鼓励,因为如果 $arr 已经包含一些值(例如字符串 来自请求变量)然后这个值将留在原地和[] 实际上可能代表字符串访问运算符。 总是更好 通过直接赋值初始化变量。

不会产生警告,但为了清楚起见,最好像您一直在做的那样通过直接赋值进行初始化。

【讨论】:

  • 有趣。使用 PHP 这么多年了,但我从来不知道这个小宝石。
猜你喜欢
  • 2020-06-22
  • 1970-01-01
  • 2012-04-15
  • 2012-01-04
  • 2021-11-20
  • 2020-06-10
  • 2012-02-01
  • 2012-08-30
  • 2015-11-21
相关资源
最近更新 更多