Question

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?

Was it helpful?

Solution

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()).

OTHER TIPS

As of php 7 you can now do the following:

foreach ($item as $key=>$value) {
    $arr[$key] = ($arr[$key] ?? 0) + other_arr[$value];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top