PHP 速记加法运算符 - 未定义的偏移量

发布于 2024-12-15 07:16:07 字数 492 浏览 0 评论 0原文

我使用 PHP 速记加法运算符来统计多维数组中特定 id 出现的次数:

$source['tally'] = array();

foreach ($items as $item) {
    $source['tally'][$item->getId()] += 1;
}

第一次遇到新 id 时,它将其“计数”值设置为 1,然后在每次找到时递增该值此后。

该代码工作完美(我得到了正确的总数),但是 PHP 每次找到新的 id 时都会给我一个“未定义的偏移量”通知。

我知道我可以关闭 php.ini 中的通知,但我想 PHP 不认可我的技术肯定是有原因的。

像这样动态创建新的键/偏移量是否被认为是不好的做法,我是否应该采取更好的方法?

请注意:为了帮助澄清以下初步反馈,我确实理解发出该通知的原因。我的问题是我是否应该对此采取行动,或者只是接受这个通知。如果我的问题不够清楚,我深表歉意。

I'm using the PHP shorthand addition operator to tally the number of times a specific id occurs within a multidimensional array:

$source['tally'] = array();

foreach ($items as $item) {
    $source['tally'][$item->getId()] += 1;
}

The first time it hits a new id, it sets its 'tally' value to 1 and then increments it each time it's found thereafter.

The code works perfectly (I get the correct totals), but PHP gives me an "Undefined Offset" notice each time it finds a new id.

I know I can just turn off notices in php.ini, but figured there must be a reason why PHP doesn't approve of my technique.

Is it considered bad practice to create a new key/offset dynamically like this, and is there a better approach I should take instead?

Please Note: To help clarify following initial feedback, I do understand why the notice is being given. My question is whether I should do anything about it or just live with the notice. Apologies if my question didn't make that clear enough.

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

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

发布评论

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

评论(4

天煞孤星 2024-12-22 07:16:07

如果您只是想隐藏通知,可以使用错误控制运算符< /a>:

$source['tally'] = array();

foreach ($items as $item) {
    @$source['tally'][$item->getId()]++;
}

但是,您通常应该初始化变量,在本例中通过在循环内添加以下代码:

if (!isset( $source['tally'][$item->getId()] ))
{
   $source['tally'][$item->getId()] = 0;
}

If you simply want to hide the notice, you can use the error control operator:

$source['tally'] = array();

foreach ($items as $item) {
    @$source['tally'][$item->getId()]++;
}

However, you should generally initialize your variables, in this case by adding the following code inside the loop:

if (!isset( $source['tally'][$item->getId()] ))
{
   $source['tally'][$item->getId()] = 0;
}
一瞬间的火花 2024-12-22 07:16:07

您必须了解 PHP 通知是一个工具。它们的存在是为了让您在编写代码时获得额外的帮助,并且能够轻松检测潜在的错误。未初始化的变量就是典型的例子。许多开发人员问:如果不强制初始化变量,为什么 PHP 会抱怨呢?因为它试图提供帮助:

$item_count = 0;
while( do_some_stuff() ){
     $iten_count++; // Notice: Undefined variable: iten_count
}
echo $item_count . ' items found';

哎呀,我输错了变量名。

$res = mysql_query('SELECT * FROM foo WHERE foo_id=' . (int)$_GET['foo_id']);
// Notice: Undefined index: foo_id

糟糕,我没有提供默认值。

您的情况只是同一情况的另一个例子。如果您递增了错误的数组元素,您想知道。

You have to understand that PHP notices are a tool. They exist so you have additional help when writing code and you are able to detect potential bugs easily. Uninitialized variables are the typical example. Many developers ask: if it's not mandatory to initialize variables, why is PHP complaining? Because it's trying to help:

$item_count = 0;
while( do_some_stuff() ){
     $iten_count++; // Notice: Undefined variable: iten_count
}
echo $item_count . ' items found';

Oops, I mistyped the variable name.

$res = mysql_query('SELECT * FROM foo WHERE foo_id=' . (int)$_GET['foo_id']);
// Notice: Undefined index: foo_id

Oops, I haven't provided a default value.

Yours is just another example of the same situation. If you're incrementing the wrong array element, you'd like to know.

赠我空喜 2024-12-22 07:16:07

使用 += (或任何其他增强赋值运算符)假定该键已存在值。由于这不是第一次遇到 ID 时的情况,因此会发出通知并假定 0

Using += (or any of the other augmented assignment operators) assumes that a value already exists for that key. Since this is not the case the first time the ID is encountered, a notice is emitted and 0 is assumed.

怀念你的温柔 2024-12-22 07:16:07

这是因为您没有初始化数组以包​​含 0 的初始值。请注意,该代码可能会起作用,但是初始化要对其执行操作的所有变量被认为是很好的做法。因此,下面的代码是您可能应该拥有的示例:

<?php
    $source['tally'] = array();

    foreach ($items as $item) {
        //For each $item in $items,
        //check if that item doesn't exist and create it (0 times).
        //Then, regardless of the previous statement, increase it by one.
        if (!isset($source['tally'][$item->getID()]) $source['tally'][$item->getID()] = 0;
        $source['tally'][$item->getId()] += 1;
    }
?>

PHP 关心它的实际原因主要是警告您该空值(就像您尝试读取它时会出现的情况一样)。这是一种错误,不是致命的、杀死脚本的错误,而是一种更微妙的安静错误。不过你还是应该修复它。

It's caused because you don't initialize your array to contain the initial value of 0. Note that the code would probably work, however it is considered good practice to initialize all the variable you are about to preform actions upon. So the following code is an example of what you should probably have:

<?php
    $source['tally'] = array();

    foreach ($items as $item) {
        //For each $item in $items,
        //check if that item doesn't exist and create it (0 times).
        //Then, regardless of the previous statement, increase it by one.
        if (!isset($source['tally'][$item->getID()]) $source['tally'][$item->getID()] = 0;
        $source['tally'][$item->getId()] += 1;
    }
?>

The actual reason why PHP cares about it, is mainly to warn you about that empty value (much like it would if you try to read it). It is a kind of an error, not a fatal, script-killing one, but a more subtle quiet one. You should still fix it though.

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