我在PHP中具有以下代码
if (is_numeric($args['myargs']['custom_value'])) {
echo 'Yes';
} else {
echo 'No';
}
它可以正常运行,但是如果未设置custom_value,那么我会在日志中得到警告。
PHP Notice: Undefined index: custom_value
我认为这只是一个通知,而不是一个错误,因此可以放心忽略吗?这样做是不好的做法吗?
答案 0 :(得分:3)
为避免警告,您应该执行以下操作
if(isset($args['myargs']['custom_value'])) {
if (is_numeric($args['myargs']['custom_value'])) {
echo 'Yes';
} else {
echo 'No';
}
}
答案 1 :(得分:2)
发生了什么
PHP看到您正在尝试使用未设置的数组元素,因此它会向您发出警告。在这种情况下这并不严重,但是您想学习避免出现这些消息。
解决方案
函数isset
将测试是否定义了数组键。
//You must first of all test isset and then is_numeric,
// else you still get the error. Research 'short circuiting' in php
if ( isset($args['myargs']['custom_value']) && is_numeric($args['myargs']['custom_value'])) {
echo 'Yes';
} else {
echo 'No';
}
如果从未定义阵列键,此解决方案还将打印“否”。
答案 2 :(得分:1)
还可以
error_reporting(0)
以php文件开头