在多维数组中向其添加新值之前,是否需要检查键是否存在?

时间:2017-12-07 11:25:55

标签: php

我记得很久以前写过代码,如下所示。在多维数组中为每个键添加值之前检查每个键的位置:

$transactions = [];

if (!isset($transactions[$account])) {
    $transactions[$account] = [];
}

if (!$transactions[$account]['cards'])) {
    $transactions[$account]['cards'] = [];
}

$transactions[$account]["cards"][] = $card;

但最近我注意到我已经开始写这个:

$transactions = [];

$transactions[$account]["cards"][] = $card;

并且一切似乎工作得很好而没有预先声明这些数组。

2 个答案:

答案 0 :(得分:2)

是的,PHP将在赋值时隐式创建中间数组(并且仅在赋值时):

  

如果[数组]还没有存在,它将被创建,所以这也是一个   另一种创建数组的方法。然而,这种做法   气馁,因为如果[数组]已经包含一些值(例如字符串   从请求变量)然后这个值将保留在该位置[]   实际上可能代表字符串访问运算符。它总是更好   通过直接赋值初始化变量。

     

http://php.net/manual/en/language.types.array.php#language.types.array.syntax.modifying

所以,是的,只要你确定你的数组结构并且你不小心使用[...]访问字符串索引而不是数组,它就可以工作并且得到明确支持你期待的。

答案 1 :(得分:0)

您无需在创建Multi维或任何数组时进行检查。 但是,当您想更新删除数组时,您需要检查。

考试:

$transactions[$account]["cards"][] = $card;
// you dont need to check here.

$transactions[$account]["cards"][] = 343; // This may not work
// When you want to update it, you need to check

if(isset($transactions[$account]["cards"]))
    $transactions[$account]["cards"] = 343;
// The above condition helps you in not breaking the script,
//if you want to assign to an array which is not created. 

祝你好运!