Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Undefined Index / Undefined Offset work arounds [duplicate]

Tags:

php

increment

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

Recently turned on errors and I'm catching the Undefined Index and Undefined Offset error on lines I'm incrementing to a new array index.

Here's a very basic example.

for($i = 0; $i<10; $i++)
{
    $arr['var1'] += $val1[$i];
    $arr['var2'] += $val2[$i];
}

I'm getting the error because on the first iteration $arr['var1'] isn't set.

I've found that both checking that the index is set

if (!isset($arr['var1'])) {
    $arr['var1'] = 0;
}
$arr['var1'] += $val1[$i];

• and •

automatically setting the index with a val of 0 before the incrementing forloop both stop the error messages.

My question is that I'll have about 150 of these to fix, what would be the best way to approach this problem. Check isset on each one, or define each one beforehand with a val of 0?

like image 461
Jeremy A Avatar asked Apr 29 '26 15:04

Jeremy A


2 Answers

You should always initialize your variables. This is absolutely a best practice across virtually every language, and it's considered an extremely bad habit to access unset variables. You should always be developing software with errors on.

Your code should read:

$arr['var1'] = $arr['var2'] = 0;
for($i = 0; $i<10; $i++)
{
    $arr['var1'] += $val1[$i];
    $arr['var2'] += $val2[$i];
}

Take the hit, fix all 150 occurrences of this problem, and then learn from your mistake. Write the code correctly the next time.

like image 145
meagar Avatar answered May 02 '26 03:05

meagar


This is personal preference, as the same functionality results from either choice. However, declaring it ahead of time will save you a conditional and a function call (which would be in the loop, repeated), so from an efficiency standpoint it's best to declare it before the loop. Typically, best practice is to declare variables before you use them. However, PHP lets you get away with things like this, which is why it's not required.

like image 29
nickb Avatar answered May 02 '26 05:05

nickb



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!