如何避免未定义的索引 [英] How to avoid undefined index
本文介绍了如何避免未定义的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何轻松避免在PHP中收到此错误/通知?
How can you easily avoid getting this error/notice in PHP?
Notice: Undefined index: test in /var/www/page.php on line 21
代码:
$table = 'test';
$preset = array();
method($preset[$table]);
数组$preset
存在,但不具有指定的索引
The array $preset
exists but not with the specified index
推荐答案
$table = 'test';
$preset = array();
if(array_key_exists($table, $preset)) {
method($preset[$table]);
}else{
// $table doesn't exist in $preset
}
或者,您可以使用 isset
:
Alternatively, you could use isset
:
$table = 'test';
$preset = array();
if(isset($preset[$table])) {
method($preset[$table]);
}else{
// $table doesn't exist in $preset
}
这篇关于如何避免未定义的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文