是否有必要在追加之前定义数组?
Is it necessary to define the array before appending to it?
小问题。
假设我有以下代码
<?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条件是否必要?
来自 official documentation on arrays(强调我的):
$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.
不会产生任何警告,但为了清楚起见,最好像您一直在做的那样通过直接赋值进行初始化。
小问题。
假设我有以下代码
<?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条件是否必要?
来自 official documentation on arrays(强调我的):
$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.
不会产生任何警告,但为了清楚起见,最好像您一直在做的那样通过直接赋值进行初始化。