在使用[]添加值之前是否需要声明PHP数组?


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

我知道没有第一行就可以使用它,但是通常会在实践中包含它。

是什么原因?没有它是否不安全?

我知道您也可以这样做:

 $arr = array(5);

但我说的是您需要一一添加项目的情况。


2
除非您喜欢有关未声明变量的通知,否则我建议进行初始化。另外,它只是编写清晰的代码(很明显$foo = array(),它不是将字符串放入数组等)。
布拉德·克里斯蒂

6
@布拉德·克里斯蒂(Brad Christie):除非不会触发此类通知。
BoltClock

3
@BoltClock:取决于您使用的版本
布拉德·克里斯蒂

Answers:


92

如果您不声明新数组,并且创建/更新数组的数据由于任何原因而失败,那么以后尝试使用该数组的任何代码都会E_FATAL因为该数组不存在。

例如,foreach()如果未声明该数组且未添加任何值,将抛出错误。但是,如果数组只是空的,则不会发生任何错误,就像您声明它的情况一样。


支持该foreach示例,因为该示例以及错误被触发的事实显然取决于您所运行的PHP版本。
Charles Sprayberry

1
我不明白那个答案。没有声明并且没有添加任何内容意味着我没有写到源代码中。
高登

2
@Gordon,如果$ something不等于1则无法正常工作的示例:if($ something == 1){$ rows [] =“ a”; $ rows [] =“ b”; } foreach($ rows as $ row){}如果将$ rows声明为$ rows = array();可以避免该错误;在if语句发生之前。
djdy 2011年

1
我同意(我投了赞成票),但是生命太短了,无法一直宣布所有内容,即使我们知道这是“正确的”事情。另外,我猜如果您担心未声明的数组,可以使用is_array()。像大多数事物一样,取决于细节。
PJ Brunet

24

只是想指出,PHP文档arrays实际上在文档中对此进行了讨论。

在PHP网站上,并附有代码段:

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

“如果$arr还不存在,将创建它,因此这也是创建数组的另一种方法。”

但是,正如其他答案所说的那样……您确实应该为变量声明一个值,因为如果不这样做,可能会发生各种不良情况。


15

php是一种松散类型的语言。这是完全可以接受的。话虽如此,真正的程序员总是声明自己的变量。


1
@戈登正是我在想什么;)
AlienWebguy

6

想想追随您的编码员!如果您只是看到$arr[] = 5,那么$arr不阅读范围中的所有前面的代码,您可能不知道会是什么。显式的$arr = array()行使它清楚。


1
在PHP 5.4.x-5.6.x中:$ arr = []也有效。
Anthony Rutledge 2015年

4

这只是个好习惯。假设您是在循环内追加数组(相当普遍的做法),然后在所述循环外访问数组。没有数组声明,如果您从未使它进入循环,则代码将引发错误。


3

我强烈建议在添加值之前声明数组。除了上面提到的所有内容之外,如果数组在循环内,您可能会无意中将元素推入数组。我刚刚观察到这造成了代价高昂的错误。

//Example code    
foreach ($mailboxes as $mailbox){
       //loop creating email list to get
       foreach ($emails as $email){
          $arr[] = $email;
       }
       //loop to get emails
       foreach ($arr as $email){
       //oops now we're getting other peoples emails
       //in other mailboxes because we didn't initialize the array
       }
}

不做什么?
ryanve

1

在使用数组之前不声明它会引起问题。我刚刚发现的一种经验是,我这样称呼此测试脚本:indextest.php?file = 1STLSPGTGUS这样可以正常工作。

//indextest.php?file=1STLSPGTGUS
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");// should give: "Notice: Undefined index: file"
print ("file = " . $file);// should give: "Notice: Undefined index: file"

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing
file['iamempty'] =

Notice: Undefined index: file in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 14
file['file'] =

Notice: Array to string conversion in D:\Server\Apache24\htdocs\DeliverText\indextest.php on line 15
file = Array
*/

现在,我只需要我购买的另一个脚本中的文件,就在我的顶部,我们可以看到数组$ file的值完全错误,而数组$ path正确:“ checkgroup.php”是有罪的。

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");
$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = o
file['otherthing'] = o
file['iamempty'] = o
file['file'] = o
file = oSTLSPGTGUS
*/

初始化数组之前,那就没问题!

//indextest.php?file=1STLSPGTGUS
require_once($_SERVER['DOCUMENT_ROOT']."/IniConfig.php");
$access = "PUBLIC";
require_once(CONFPATH . "include_secure/checkgroup.php");

$path = array();
$file = array();

$path['templates']     = './mytemplates/';
$file['template']      = 'myindex.tpl.php';
$file['otherthing']      = 'otherthing.php';
$file['iamempty']    = '';

print ("path['templates'] = " . $path['templates'] . "<br>");
print ("file['template'] = " . $file['template'] . "<br>");
print ("file['otherthing'] = " . $file['otherthing'] . "<br>");
print ("file['iamempty'] = " . $file['iamempty'] . "<br>");

print ("file['file'] = " . $file['file'] . "<br>");
print ("file = " . $file);

//the Output is:
/*
path['templates'] = ./mytemplates/
file['template'] = myindex.tpl.php
file['otherthing'] = otherthing.php
file['iamempty'] =
file['file'] =
file = Array
*/

这就是我意识到初始化变量的重要性,因为我们永远不知道以后会遇到什么问题,而只是为了节省时间,最终可能会浪费更多。我希望这会对像我这样不专业的人有所帮助。


1

古老的问题,但我同意,因为这是一个用例,如果未声明数组,则代码更简单。

假设您有一个需要在其属性之一上建立索引的对象列表。

// $list is array of objects, all having $key property.
$index = [];
foreach ($list as $item)
    $index[$item->key][] = $item; // Dont care if $index[$item->key] already exists or not.

0

这取决于您的错误检查。如果您有关于严格的错误报告,则会给您通知,但从技术上讲,如果没有它,它仍然可以工作。


0

如果您需要将其用作全局变量或想在不同的函数中一次又一次地重用同一数组,则该方法很好


0

这是你的代码

$var[]  = 2;
print_r($var)

工作正常!直到有人在您的迷人代码之前声明相同的变量名

$var = 3; 

$var[]  = 2;
print_r($var)

警告:不能将标量值用作数组

糟糕!

这是一种可能(有时无法预测)的情况,因此$var = array()需要

$var = 3;
$var = array();
$var[]  = 2;
print_r($var)

输出量

Array
(
    [0] => 2
)

-1

同意@djdy,这只是我想发布的一种选择:

<?php

// Passed array is empty, so we'll never have $items variable available.
foreach (array() AS $item)
    $items[] = $item;

isset($items) OR $items = array(); // Declare $items variable if it doesn't exist

?>

这一切的意义何在?关于字面上什么都没有的事,似乎已经很不合时宜了。
BoltClock

无需预先声明$ items变量,您只需检查是否存在循环即可。
奥塔尔
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.