Ben
Ben

Reputation: 68588

Is it good practice to initialize the elements in an associative array in php?

I'm finding myself doing a lot of things with associative arrays in PHP.

I was doing this:

 foreach ($item as $key=>$value) {
     if ($arr[$key] == null) {
         $arr[$key] = 0; 
     }
     $arr[$key] += $other_arr[$value];
 }

But then I realised that it works fine if I exclude the line that initializes $arr[$key], presumably since it's null which is treated as the same as 0.

Is making that kind of assumption safe in php? And if it's safe, is it a good idea?

Upvotes: 1

Views: 814

Answers (2)

alanmanderson
alanmanderson

Reputation: 8200

As of php 7 you can now do the following:

foreach ($item as $key=>$value) {
    $arr[$key] = ($arr[$key] ?? 0) + other_arr[$value];
}

Upvotes: 0

Greg
Greg

Reputation: 321598

It is safe but I'd recommend against it. If you put your error reporting up to E_NOTICES you'll see your code producing a lot of them, masking any real errors (such as a mistyped variable name).

What you should really be doing is:

if (!isset($arr[$key]))
    $arr[$key] = 0;

This won't raise a notice (but be very careful not to mis-type $arr inside isset()).

Upvotes: 7

Related Questions