简体   繁体   中英

Do I need to check if keys exist before adding new values to it in multidimensional arrays?

I remember writing code a long time ago like seen below. Where you check each key before adding value to it in multidimensional arrays:

$transactions = [];

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

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

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

but recently I noticed that I have started writing this:

$transactions = [];

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

and everything seems to work just fine without declaring those arrays beforehand.

Yes, PHP will implicitly create intermediate arrays on assignment (and only on assignment):

If [the array] 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 [the array] already contains some value (eg 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.

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

So, yes, it works and is explicitly supported, as long as you're sure about your array structures and you're not accidentally using [...] to access a string index instead of the array you expected.

You dont need to check when you create the Multi dimensional or any Array . But you need to check, when you want to Update or Delete the array.

Examle:

$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. 

Good Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM