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

I find myself doing a lot of things with associative arrays in PHP.

I did it:

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

      

But then I realized that it works great if I exclude the line that initializes $ arr [$ key], presumably because it is null, which is treated as 0.

Is such an assumption safe in php? And if it's safe, is that a good idea?

+1


source to share


2 answers


It's safe, but I would recommend against it. If you pass the error message to E_NOTICES, you will see that your code produces a lot of them, masking any real errors (such as the name of the erroneous variable).

What you really should be doing:



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

      

This will not trigger a notification (but be very careful not to mistakenly enter $ arr inside isset ()).

+7


source


Starting from, php 7

you can do the following:



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

      

0


source







All Articles