我正在运行一个PHP脚本,并继续收到错误,如:
注意:未定义变量my_variable_name在C:\wamp\www\mypath\index.php第10行
注意:第11行未定义索引:my_index C:\wamp\www\mypath\index.php
警告:在C:\wamp\www\mypath\index.php第11行未定义数组键“my_index”
第10和11行是这样的:
echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
这些错误消息的含义是什么?
为什么他们会突然出现?我曾经使用这个脚本多年,从来没有任何问题。
我该如何修复它们?
这是一个一般参考问题,供人们链接作为副本,而不是需要一遍又一遍地解释这个问题。我觉得这很有必要,因为现实世界中关于这个问题的答案都非常具体。
相关元讨论:
如何应对重复的问题?
“参考问题”有意义吗?
未定义的索引意味着在您请求的数组中,数组索引不可用。例如,
<?php
$newArray[] = {1, 2, 3, 4, 5};
print_r($newArray[5]);
?>
一个未定义的变量意味着你完全没有使用一个现有的变量,或者这个变量没有定义或初始化。例如,
<?php print_r($myvar); ?>
未定义的偏移量意味着在数组中请求一个不存在的键。解决这个问题的方法是在使用前检查:
php> echo array_key_exists(1, $myarray);
这些注意是因为您没有定义used变量,并且my_index键没有出现在$my_array变量中。
这些通知每次都会被触发,因为您的代码不正确,但可能您没有通知的报告。
解决bug:
$my_variable_name = "Variable name"; // defining variable
echo "My variable value is: " . $my_variable_name;
if(isset($my_array["my_index"])){
echo "My index value is: " . $my_array["my_index"]; // check if my_index is set
}
另一种表达方式是:
ini_set("error_reporting", false)
在PHP中,首先需要定义变量。之后你就可以使用它了。
我们可以以一种非常有效的方式检查变量是否定义!
// If you only want to check variable has value and value has true and false value.
// But variable must be defined first.
if($my_variable_name){
}
// If you want to check if the variable is defined or undefined
// Isset() does not check that variable has a true or false value
// But it checks the null value of a variable
if(isset($my_variable_name)){
}
简单的解释
// It will work with: true, false, and NULL
$defineVariable = false;
if($defineVariable){
echo "true";
}else{
echo "false";
}
// It will check if the variable is defined or not and if the variable has a null value.
if(isset($unDefineVariable)){
echo "true";
}else{
echo "false";
}