PHP速记加法运算符 - 未定义偏移 [英] PHP Shorthand Addition Operator - Undefined Offset

查看:422
本文介绍了PHP速记加法运算符 - 未定义偏移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的PHP速记加法运算符相符的次数多维数组内发生的特定ID:

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

它击中一个新的ID第一次,它会将其理货值设置为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.

在code完美地工作(我得到正确的总计),但是PHP给了我一个未定义偏移每次看到它找到一个新的ID。

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

我知道我可以只关闭在php.ini通知,但想通必须有一个原因PHP不同意我的技术。

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.

推荐答案

如果您只是想隐藏的通知,您可以使用的错误控制运算符

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()]++;
}

但是,通常应通过添加以下code循环内初始化的变量,在这种情况下:

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

这篇关于PHP速记加法运算符 - 未定义偏移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆