我正在运行一个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版本,现在升级了PHP,这就是为什么它多年来一直没有任何错误。

在php4之前,如果你使用变量而没有定义它,就不会出现错误,但从php5开始,它会抛出类似上述问题的代码错误。

在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";
}

获取输入字符串的最佳方法是:

$value = filter_input(INPUT_POST, 'value');

这一行代码几乎相当于:

if (!isset($_POST['value'])) {
    $value = null;
} elseif (is_array($_POST['value'])) {
    $value = false;
} else {
    $value = $_POST['value'];
}

如果你确实想要一个字符串值,就像:

$value = (string)filter_input(INPUT_POST, 'value');

在PHP 7.0中,现在可以使用空合并操作符:

echo "My index value is: " . ($my_array["my_index"] ?? '');

Is等于:

echo "My index value is: " . (isset($my_array["my_index"]) ? $my_array["my_index"] : '');

PHP 7.0手册