&引用;注意:未定义变量"&引用;注意:未定义索引";,及;注意:未定义的偏移量;使用PHP

&引用;注意:未定义变量"&引用;注意:未定义索引";,及;注意:未定义的偏移量;使用PHP,php,arrays,variables,warnings,undefined-index,Php,Arrays,Variables,Warnings,Undefined Index,我正在运行一个PHP脚本,并继续收到如下错误: 注意:未定义变量:第10行C:\wamp\www\mypath\index.php中的my\u variable\u name 注意:未定义索引:第11行的my_index C:\wamp\www\mypath\index.php 第10行和第11行如下所示: echo "My variable value is: " . $my_variable_name; echo "My index value is: &quo

我正在运行一个PHP脚本,并继续收到如下错误:

注意:未定义变量:第10行C:\wamp\www\mypath\index.php中的my\u variable\u name

注意:未定义索引:第11行的my_index C:\wamp\www\mypath\index.php

第10行和第11行如下所示:

echo "My variable value is: " . $my_variable_name;
echo "My index value is: " . $my_array["my_index"];
这些错误消息的含义是什么

为什么它们突然出现?我使用这个脚本多年了,从来没有遇到过任何问题

我怎样修理它们


这是一个一般性的参考问题,供人们重复链接,而不必反复解释问题。我觉得这是必要的,因为在这个问题上,大多数现实世界的答案都非常具体

相关元讨论:

试试这些

问题1:此通知意味着$varname不可用 在当前的范围内定义 剧本

问题2:在使用任何可疑变量之前使用isset()、empty()条件效果良好

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

// 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()放置在所有文件中

通常是因为“糟糕的编程”,以及现在或以后出错的可能性

  • 如果是错误的,首先对变量进行正确赋值:$varname=0
  • 如果它确实只是偶尔定义的,那么在使用它之前测试它:
    If(isset($varname))
  • 如果是因为你拼错了,就纠正它
  • 甚至可能在您的PHP设置中出现警告

  • 这意味着您正在测试、评估或打印尚未分配任何内容的变量。这意味着您要么有输入错误,要么需要先检查变量是否初始化为某个值。检查逻辑路径,可以在一个路径中设置,但不能在另一个路径中设置。

    注意:未定义变量 来自世界的巨大智慧:

    在将一个文件包含到另一个使用相同变量名的文件中时,依赖未初始化变量的默认值是有问题的。它也是一个打开的大调。在使用未初始化的变量时会发出级别错误,但在向未初始化的数组追加元素时不会发出级别错误。语言构造可用于检测变量是否已初始化。此外,更理想的解决方案是,因为如果变量未初始化,它不会生成警告或错误消息

    发件人:

    如果变量不存在,则不会生成警告。这意味着 empty()本质上是的简明等价物!isset($var)| |$var ==false

    这意味着您只能使用
    empty()
    来确定变量是否已设置,此外,它还会根据以下内容检查变量:
    0
    0.0
    “0”
    null
    false
    []

    例如:

    在中测试上述代码段

    尽管PHP不需要变量声明,但它还是建议使用它,以避免出现一些安全漏洞或bug,在这些漏洞或bug中,人们会忘记为稍后在脚本中使用的变量赋值。PHP在未声明变量的情况下所做的是发出一个非常低级的错误,
    E_NOTICE
    ,默认情况下甚至没有报告这个错误,而是在开发过程中手动报告的

    处理这一问题的方法:

  • 建议:声明变量,例如,当您尝试将字符串附加到未定义的变量时。或在引用它们之前使用/检查它们是否已声明,如中所示:

    //Initializing variable
    $value = ""; //Initialization value; Examples
                 //"" When you want to append stuff later
                 //0  When you want to add numbers later
    //isset()
    $value = isset($_POST['value']) ? $_POST['value'] : '';
    //empty()
    $value = !empty($_POST['value']) ? $_POST['value'] : '';
    
    这在PHP 7.0中变得更加清晰,现在您可以使用:

  • 为E_通知设置一个,并将消息重定向到标准输出之外(可能到日志文件):

  • 从报告中禁用E_通知。排除E_通知的快速方法是:

    error_reporting( error_reporting() & ~E_NOTICE )
    
  • 使用命令来抑制错误

  • 注意:强烈建议只实施第1点

    注意:未定义索引/未定义偏移 当您(或PHP)尝试访问数组的未定义索引时,会出现此通知

    处理这一问题的方法:

  • 在访问该索引之前,请检查该索引是否存在。为此,您可以使用或:

  • 当语言构造试图访问不存在的数组索引时,它可能会生成:

    list($a, $b) = array(0 => 'a');
    //or
    list($one, $two) = explode(',', 'test string');
    
  • 两个变量用于访问两个数组元素,但是只有一个数组元素index
    0
    ,因此这将生成:

    注意:未定义的偏移量:1

    $\u POST
    /
    $\u GET
    /
    $\u SESSION
    变量 使用
    $\u POST
    $\u GET
    $\u SESSION
    时,经常会出现上述注意事项。对于
    $\u POST
    $\u GET
    ,您只需在使用它们之前检查索引是否存在。对于
    $\u会话
    ,您必须确保会话以开始,并且索引也存在

    还请注意,所有3个变量都是和,都是大写

    相关的:

    错误显示 对于不需要的和冗余的通知,可以使用专用于»隐藏«未定义变量/索引消息

    $var = @($_GET["optional_param"]);
    
    • 这通常是不鼓励的。新来者往往过度使用它
    • 对于应用程序逻辑中的深层代码(忽略不应该声明的未声明变量),例如函数参数或循环中的代码,这是非常不合适的
    • isset?上有一个优势:
      超级抑制。通知仍然可以收到
      set_error_handler('myHandlerForMinorErrors', E_NOTICE | E_STRICT)
      
      error_reporting( error_reporting() & ~E_NOTICE )
      
      //isset()
      $value = isset($array['my_index']) ? $array['my_index'] : '';
      //array_key_exists()
      $value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
      
      list($a, $b) = array(0 => 'a');
      //or
      list($one, $two) = explode(',', 'test string');
      
      $var = @($_GET["optional_param"]);
      
      var_dump($_GET);
      var_dump($_POST);
      //print_r($_REQUEST);
      
      print_r($_SERVER);
      
      function ifexists($varname)
      {
        return(isset($$varname)?$varname:null);
      }
      
      <?=ifexists('name')?>
      
      function ifexistsidx($var,$index)
      {
        return(isset($var[$index])?$var[$index]:null);
      }
      
      <?=ifexistsidx($_REQUEST,'name')?>
      
      $a=10;
      if($a==5) { $user_location='Paris';} else { }
      echo $user_location;
      
      $a=10;
      if($a==5) { $user_location='Paris';} else { $user_location='SOMETHING OR BLANK'; }
      echo $user_location;
      
      $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
      error_reporting(E_ALL); // making sure all notices are on
      
      function idxVal(&$var, $default = null) {
               return empty($var) ? $var = $default : $var;
        }
      
      echo idxVal($arr['test']);         // returns null without any notice
      echo idxVal($arr['hey ho'], 'yo'); // returns yo and assigns it to array index, nice
      
      ?>
      
      $user_location = null;
      
      $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');
      
      // Echo whatever the hell this is
      <?=$_POST['something']?>
      
      // If this is set, echo a filtered version
      <?=isset($_POST['something']) ? html($_POST['something']) : ''?>
      
      ; Common Values:
      ;   E_ALL (Show all errors, warnings and notices including coding standards.)
      ;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
      ;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
      ;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
      ; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
      ; Development Value: E_ALL
      ; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
      ; http://php.net/error-reporting
      error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
      
      function foo()
      {
          $my_variable_name = '';
      
          //....
      
          if ($my_variable_name) {
              // perform some logic
          }
      }
      
      // verbose way - generally better
      if (isset($my_array['my_index'])) {
          echo "My index value is: " . $my_array['my_index'];
      }
      
      // non-verbose ternary example - I use this sometimes for small rules.
      $my_index_val = isset($my_array['my_index'])?$my_array['my_index']:'(undefined)';
      echo "My index value is: " . $my_index_val;   
      
      $my_array = array(
          'my_index' => ''
      );
      
      //...
      
      $my_array['my_index'] = 'new string';
      
      echo "My index value is: " . ($my_array["my_index"] ?? '');
      
      echo "My index value is: " . (isset($my_array["my_index"]) ? $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);
      
      class Person
      {
          protected $firstName;
          protected $lastName;
      
          public function setFullName($first, $last)
          {
              // Correct
              $this->firstName = $first;
      
              // Incorrect
              $lastName = $last;
      
              // Incorrect
              $this->$lastName = $last;
          }
      }
      
      $query = "SELECT col1 FROM table WHERE col_x = ?";
      
      print_r($row['col1']);
      print_r($row['col2']); // undefined index thrown
      
      while( $row = fetching_function($query) ) {
      
          echo $row['col1'];
          echo "<br>";
          echo $row['col2']; // undefined index thrown
          echo "<br>";
          echo $row['col3']; // undefined index thrown
      
      }
      
      <!-- The data encoding type, enctype, MUST be specified as below -->
      <form enctype="multipart/form-data" action="__URL__" method="POST">
          <!-- MAX_FILE_SIZE must precede the file input field -->
          <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
          <!-- Name of input element determines name in $_FILES array -->
          Send this file: <input name="userfile" type="file" />
          <input type="submit" value="Send File" />
      </form>
      
      <?php
      // In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
      // of $_FILES.
      
      $uploaddir = '/var/www/uploads/';
      $uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
      
      echo '<pre>';
      if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
          echo "File is valid, and was successfully uploaded.\n";
      } else {
          echo "Possible file upload attack!\n";
      }
      
      echo 'Here is some more debugging info:';
      print_r($_FILES);
      
      print "</pre>";
      
      ?>
      
      $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)
      
      //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 variable is define or undefine
      //Isset() does not check that variable has true or false value
      //But it check null value of variable
      if(isset($my_variable_name)){
      
      }
      
      //It will work with :- true,false,NULL
      $defineVarialbe = false;
      if($defineVarialbe){
          echo "true";
      }else{
          echo "false";
      }
      
      //It will check variable is define or not and variable has null value.
      if(isset($unDefineVarialbe)){
          echo "true";
      }else{
          echo "false";
      }
      
      <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>
      
      $newVariable = isset($thePotentialData) ? $thePotentialData : null;
      
      $newVariable = $thePotentialData ?? null;
      
      if (isset($thePotentialData)) {
          $newVariable = $thePotentialData;
      } else {
          $newVariable = null;
      }
      
      echo 'Your name is: ' . isset($name) ? $name : 'You did not provide one';
      
      $foreName = getForeName(isset($userId) ? $userId : null);
      
      function getForeName($userId)
      {
          if ($userId === null) {
              // Etc
          }
      }
      
      153    foreach($cities as $key => $city){
      154        if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
      
      foreach($cities as $key => $city){
          if(array_key_exists($key, $citiesCounterArray)){
              if(($city != 'London') && ($city != 'Madrid') && ($citiesCounterArray[$key] >= 1)){
      
      ini_set('error_reporting', 'on');
      ini_set('display_errors', 'on');
      error_reporting(E_ALL);
      
      if ($my == 9) {
       $test = 'yes';  // Will produce error as $my is not 9.
      }
      echo $test;
      
      $test = NULL;
      if ($my == 9) {
       $test = 'yes';  // Will produce error as $my is not 9.
      }
      echo $test;
      
      if(isset($_POST['param'])){
          $param = $_POST['param'];
      } else {
      #do something else
      }