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?
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:
Take the hit, fix all 150 occurrences of this problem, and then learn from your mistake. Write the code correctly the next time.