在php中的关联数组中初始化元素是否是一种好习惯? [英] Is it good practice to initialize the elements in an associative array in php?

查看:70
本文介绍了在php中的关联数组中初始化元素是否是一种好习惯?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现自己在PHP中使用关联数组做很多事情.

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

我正在这样做:

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

但是后来我意识到,如果我排除初始化$ arr [$ key]的行,那可能很好用,大概是因为它为null,它被视为与0相同.

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.

在php中使这种假设安全吗?如果安全的话,这是个好主意吗?

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

推荐答案

这是安全的,但我建议不要这样做. 如果您将错误报告提高到E_NOTICES,您将看到代码产生了大量错误,从而掩盖了所有实际错误(例如,错误键入的变量名).

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

您真正应该做的是:

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

这不会引起通知(但请注意不要在isset()中错误键入$ arr).

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

这篇关于在php中的关联数组中初始化元素是否是一种好习惯?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆