是否有必要在使用 [] 添加值之前声明 PHP 数组? [英] Is it necessary to declare PHP array before adding values with []?

查看:49
本文介绍了是否有必要在使用 [] 添加值之前声明 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);

但我说的是需要一个一个添加项目的情况.

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

推荐答案

如果您没有声明一个新数组,并且创建/更新该数组的数据由于任何原因而失败,那么任何以后尝试使用该数组的代码数组将 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天全站免登陆