是否有必要在使用 [] 添加值之前声明 PHP 数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8246047/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it necessary to declare PHP array before adding values with []?
提问by ryanve
$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.
但我说的是需要一项一项添加项目的情况。
回答by djdy
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.
如果您不声明新数组,并且创建/更新数组的数据因任何原因失败,则任何未来尝试使用该数组的代码都将E_FATAL
因为该数组不存在。
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.
例如,foreach()
如果未声明数组且未向其中添加任何值,则会引发错误。但是,如果数组只是空的,则不会发生错误,就像您声明它的情况一样。
回答by Charles Sprayberry
Just wanted to point out that the PHP documentation on arrays
actually talks about this in documentation.
只是想指出PHP 文档arrays
实际上在文档中讨论了这一点。
From the PHP site, with accompanying code snippet:
来自 PHP 站点,附带代码片段:
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
"If
$arr
doesn't exist yet, it will be created, so this is also an alternative way to create an array."
“如果
$arr
还不存在,它将被创建,所以这也是创建数组的另一种方式。”
But, as the other answers stated...you really should declare a value for your variables because all kind of bad things can happen if you don't.
但是,正如其他答案所述......你真的应该为你的变量声明一个值,因为如果你不这样做,所有的坏事都会发生。
回答by AlienWebguy
Php is a loosely typed language. It's perfectly acceptable. That being said, real programmers always declare their vars.
PHP 是一种松散类型的语言。这是完全可以接受的。话虽如此,真正的程序员总是声明他们的变量。
回答by Rob Agar
Think of the coders who come after you! If you just see $arr[] = 5
, you have no idea what $arr
might be without reading all the preceding code in the scope. The explicit $arr = array()
line makes it clear.
想想那些追随你的程序员!如果你只是看到$arr[] = 5
,如果$arr
不阅读范围内的所有前面的代码,你就不知道可能会发生什么。明确的$arr = array()
行使其清楚。
回答by Julien
it's just good practice. Let's say you were appending to your array inside a loop (fairly common practice), but then accessing the array outside of said loop. Without an array declaration, your code would throw errors if you never made it into the loop.
这只是很好的做法。假设您在循环内将数组附加到数组中(相当常见的做法),然后在所述循环外访问数组。如果没有数组声明,如果您从未将其放入循环中,您的代码就会抛出错误。
回答by ykay says Reinstate Monica
I strongly recommend to declare the array before adding values. Besides everything mentioned above, if the array is inside a loop you might unintentionally push elements into your array. I just observed this creating a costly bug.
我强烈建议在添加值之前声明数组。除了上面提到的所有内容,如果数组在循环内,您可能会无意中将元素推入数组。我只是观察到这会造成一个代价高昂的错误。
//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
}
}
回答by Dan Bon
By not declaring an array before using it can really cause problems. One experience I just found, I called this test script like this: indextest.php?file=1STLSPGTGUS This works as expected.
在使用数组之前不声明它确实会导致问题。我刚刚发现的一个经验是,我将这个测试脚本称为: 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
*/
Now I will just require a file, from another script I bought, at the top of mine and we can see how values are completly wrong for the array $file while array $path is OK: "checkgroup.php" is the guilty one.
现在我只需要一个文件,来自我购买的另一个脚本,在我的顶部,我们可以看到数组 $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
*/
Initialising the array before, then no problem!
之前初始化数组,然后没问题!
//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
*/
That's how I realised how important it is to initialise variables as we never know what problem we might end up with later, and just for wanting to save time we might end up wasting even more at the end. I hope this will be helpful for those like me who are not professional.
这就是我如何意识到初始化变量的重要性,因为我们永远不知道我们以后可能会遇到什么问题,而只是为了节省时间,我们最终可能会浪费更多。希望对我这种非专业人士有所帮助。
回答by jaisson
Old question but I share this as this is one use case where code is simpler if arrays are not declared.
老问题,但我分享这个,因为这是一个用例,如果未声明数组,代码会更简单。
Say you have a list of objects you need to index on one of their properties.
假设您有一个对象列表,您需要对其属性之一进行索引。
// $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.
回答by Rain
This is your code
这是你的代码
$var[] = 2;
print_r($var)
Works fine! until someone declares the same variable name before your charming code
工作正常!直到有人在你迷人的代码之前声明了相同的变量名
$var = 3;
$var[] = 2;
print_r($var)
Warning: Cannot use a scalar value as an array
警告:不能将标量值用作数组
Oops!
哎呀!
This is one possible (sometimes unpredictable) case, so yes $var = array()
is needed
这是一种可能的(有时是不可预测的)情况,所以$var = array()
需要是
$var = 3;
$var = array();
$var[] = 2;
print_r($var)
Output
输出
Array
(
[0] => 2
)
回答by brenjt
It depends on your error checking. If you have error reporting on strict it'll give you a notice but it should still technically work without it.
这取决于您的错误检查。如果你有严格的错误报告,它会给你一个通知,但在没有它的情况下它在技术上仍然可以工作。