我正在运行一个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 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手册

其他回答

可能你使用的是旧的PHP版本,现在升级了PHP,这就是为什么它多年来一直没有任何错误。

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

HTML表单提交后变量不存在的一个常见原因是表单元素没有包含在<form>标记中:

示例:<表单>中不包含的元素

<form action="example.php" method="post">
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

<select name="choice">
    <option value="choice1">choice 1</option>
    <option value="choice2">choice 2</option>
    <option value="choice3">choice 3</option>
    <option value="choice4">choice 4</option>
</select>

示例:元素现在包含在<表单>中

<form action="example.php" method="post">
    <select name="choice">
        <option value="choice1">choice 1</option>
        <option value="choice2">choice 2</option>
        <option value="choice3">choice 3</option>
        <option value="choice4">choice 4</option>
    </select>
    <p>
        <input type="text" name="name" />
        <input type="submit" value="Submit" />
    </p>
</form>

我不想禁用通知功能,因为它很有帮助,但我想避免太多的输入。

我的解是这个函数:

function ifexists($varname)
{
  return(isset($$varname) ? $varname : null);
}

因此,如果我想引用$name和echo if存在,我简单地写:

<?= ifexists('name') ?>

对于数组元素:

function ifexistsidx($var,$index)
{
  return(isset($var[$index]) ? $var[$index] : null);
}

在一个页面中,如果我想引用$_REQUEST['name']:

<?= ifexistsidx($_REQUEST, 'name') ?>

试试这些

Q1:这个通知意味着$varname不是 的当前范围内定义 脚本。 Q2:在使用任何可疑变量之前,使用isset(), empty()条件可以很好地工作。

// recommended solution for recent PHP versions
$user_name = $_SESSION['user_name'] ?? '';

// pre-7 PHP versions
$user_name = '';
if (!empty($_SESSION['user_name'])) {
     $user_name = $_SESSION['user_name'];
}

或者,作为一个快速而肮脏的解决方案:

// not the best solution, but works
// in your php setting use, it helps hiding site wide notices
error_reporting(E_ALL ^ E_NOTICE);

关于会话的注意事项:

当使用会话时,session_start();必须放置在使用会话的所有文件中。 http://php.net/manual/en/features.sessions.php

未定义的索引意味着在您请求的数组中,数组索引不可用。例如,

<?php
    $newArray[] = {1, 2, 3, 4, 5};
    print_r($newArray[5]);
?>

一个未定义的变量意味着你完全没有使用一个现有的变量,或者这个变量没有定义或初始化。例如,

<?php print_r($myvar); ?>

未定义的偏移量意味着在数组中请求一个不存在的键。解决这个问题的方法是在使用前检查:

php> echo array_key_exists(1, $myarray);