问题描述
最近打开了错误,我在行中捕获了Undefined Index和Undefined Offset错误,我正在增加到新的数组索引.
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];
}
我收到错误消息是因为在第一次迭代中未设置$ arr ['var1'].
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];
•和•
在递增的forloop都停止错误消息之前,将val的索引自动设置为0.
automatically setting the index with a val of 0 before the incrementing forloop both stop the error messages.
我的问题是,我将修复约150个问题,这是解决此问题的最佳方法.检查每一个的isset,或者预先将每个val的值定义为0?
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?
推荐答案
您应该始终初始化变量.这对于几乎所有语言而言绝对是最佳实践,并且访问未设置的变量被视为一种极坏的习惯.您应该始终在错误 on 上开发软件.
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.
您的代码应为:
$arr['var1'] = $arr['var2'] = 0;
for($i = 0; $i<10; $i++)
{
$arr['var1'] += $val1[$i];
$arr['var2'] += $val2[$i];
}
选择要解决的问题,修复所有150个出现的问题,然后从错误中吸取教训.下次正确编写代码.
Take the hit, fix all 150 occurrences of this problem, and then learn from your mistake. Write the code correctly the next time.
这篇关于PHP未定义索引/未定义偏移量变通方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!