我正在运行一个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);
我一直使用自己的有用函数exst()自动声明变量。
您的代码将是-
$greeting = "Hello, " . exst($user_name, 'Visitor') . " from " . exst($user_location);
/**
* Function exst() - Checks if the variable has been set
* (copy/paste it in any place of your code)
*
* If the variable is set and not empty returns the variable (no transformation)
* If the variable is not set or empty, returns the $default value
*
* @param mixed $var
* @param mixed $default
*
* @return mixed
*/
function exst(& $var, $default = "")
{
$t = "";
if (!isset($var) || !$var) {
if (isset($default) && $default != "")
$t = $default;
}
else {
$t = $var;
}
if (is_string($t))
$t = trim($t);
return $t;
}
在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";
}