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

发布于 2024-12-17 16:41:49 字数 230 浏览 0 评论 0原文

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

我知道它不需要第一行就可以工作,但它经常包含在实践中。

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

我知道你也可以这样做:

 $arr = array(5);

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

听风吹 2024-12-24 16:41:49

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

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

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.

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.

云柯 2024-12-24 16:41:49

只是想指出 关于数组的 PHP 文档< /a> 实际上在文档中讨论了这一点。

来自 PHP 站点,附带代码片段:

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

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

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

Just wanted to point out that the PHP documentation on arrays actually talks about this in documentation.

From the PHP site, with accompanying code snippet:

$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."

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.

一曲爱恨情仇 2024-12-24 16:41:49

Php 是一种松散类型的语言。这是完全可以接受的。

Php is a loosely typed language. It's perfectly acceptable.

七婞 2024-12-24 16:41:49

想想那些追随你的程序员吧!如果您只看到 $arr[] = 5,则在不阅读范围内所有前面的代码的情况下,您不知道 $arr 可能是什么。明确的 $arr = array() 行使这一点变得清晰。

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.

2024-12-24 16:41:49

这只是一个很好的做法。假设您要在循环内附加到数组(相当常见的做法),但然后在所述循环之外访问数组。如果没有数组声明,如果您从未进入循环,您的代码就会抛出错误。

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.

东风软 2024-12-24 16:41:49

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

//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
       }
}

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
       }
}
青萝楚歌 2024-12-24 16:41:49

在使用数组之前不声明它确实会导致问题。
我刚刚发现的一种体验,我这样调用这个测试脚本: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
*/

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

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

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

弄潮 2024-12-24 16:41:49

老问题,但我分享这个,因为这是一个用例,如果未声明数组,代码会更简单。

假设您有一个对象列表,需要根据其属性之一建立索引。

// $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.

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.
梦行七里 2024-12-24 16:41:49

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

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.

梦幻的心爱 2024-12-24 16:41:49

当您需要它作为全局变量或想要在不同的函数中一次又一次地重用相同的数组时,它很有用

Its good in case when you need it as a global variable or want to reuse the same array again and again in different functions

以歌曲疗慰 2024-12-24 16:41:49

这是你的代码

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

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 = 3;
$var = array();
$var[]  = 2;
print_r($var)

Output

Array
(
    [0] => 2
)
挽梦忆笙歌 2024-12-24 16:41:49

对于 foreach 循环,如果您不确定数据,那么您可以执行以下操作:

foreach($users ?? [] as $user) {
    // Do things with $user
}

如果未设置 $users (空合并会 isset($users))然后你会得到空数组[],因此PHP不会循环foreach,因为没有任何东西可以循环 - 没有错误、警告或通知。

我不同意评论/答案中的一些观点,我认为您不应该仅仅为了它而简单地声明空数组或初始化变量,作为某种安全网。在我看来,这种方法是糟糕的编程。必要时明确执行。

老实说,如果您必须初始化一个空数组,请考虑代码是否可以更好地结构化,以及稍后如何检查数据等等。

下面的代码是毫无意义的,它没有显示“意图”,它只会让人们困惑为什么要初始化它(充其量只是一些毫无意义的阅读和处理):

$user = [];
$user['name'] = ['bob'];

第二行还声明了新数组并且永远不会失败。

For foreach loops if you're unsure of the data, then you can do this:

foreach($users ?? [] as $user) {
    // Do things with $user
}

If $users is not set (null coalesce does isset($users)) then you'll get the empty array [] and thus PHP won't loop the foreach as there's nothing to loop - no errors, warnings, or notices.

I disagree with some in the comments/answers, I don't think you should simply declare empty arrays or initialise variables just for the sake of it, as some kind of safety net. Such approaches is bad programming in my opinion. Do it explicitly when it's necessary.

And to be honest, if you have to initialise an empty array, consider if the code could be better structured, how you check for data later on or whatever.

The following code is pointless, it doesn't show "intent" it can just confuse people as to why it's initialised (at best it's just something pointless to read and process):

$user = [];
$user['name'] = ['bob'];

The 2nd line also declares the new array and will never fail.

胡渣熟男 2024-12-24 16:41:49

同意@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

?>

Agree with @djdy, just one alternative I'd love to post:

<?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

?>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文