是否有必要用[]增加值之前申报PHP数组? [英] Is it necessary to declare PHP array before adding values with []?

查看:112
本文介绍了是否有必要用[]增加值之前申报PHP数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$arr = array(); // is this line needed?
$arr[] = 5;

我知道它不工作的第一线,但它通常包括在实践中。

I know it works without the first line, but it's often included in practice.

这是什么原因?它是不安全的,没有它?

What is the reason? Is it unsafe without it?

我知道你也可以做到这一点:

I know you can also do this:

 $arr = array(5);

但我说的是,你需要通过一个新增项目1例。

but I'm talking about cases where you need to add items one by one.

推荐答案

如果你不申报新阵列,并创建/更新以任何理由,那么任何未来code试图在阵列出现故障的数据使用数组将 E_FATAL 因为数组不存在。

If you don't declare a new array, and the data that creates / updates the array fails for any reason, then any future code that tries to use the array will E_FATAL because the array doesn't exist.

例如,的foreach()将如果阵列未声明,并且添加到它没有值抛出一个错误。但是,如果阵列仅仅是空的,因为会出现这种情况了,你宣布它不会发生错误。

For example, foreach() will throw an error if the array was not declared and no values were added to it. However, no errors will occur if the array is simply empty, as would be the case had you declared it.

这篇关于是否有必要用[]增加值之前申报PHP数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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