Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Shorthand Addition Operator - Undefined Offset

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.

like image 288
cantera Avatar asked Oct 27 '25 03:10

cantera


2 Answers

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.

like image 108
Álvaro González Avatar answered Oct 29 '25 19:10

Álvaro González


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.

like image 21
Ignacio Vazquez-Abrams Avatar answered Oct 29 '25 18:10

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!