📜  如何避免PHP的未定义偏移错误?

📅  最后修改于: 2022-05-13 01:54:11.410000             🧑  作者: Mango

如何避免PHP的未定义偏移错误?

数组中不存在的偏移量称为未定义偏移量。未定义偏移错误类似于Java的ArrayOutOfBoundException。如果我们访问一个不存在的索引或者一个空的偏移量,就会导致一个未定义的偏移量错误。
示例:以下PHP代码解释了我们如何访问数组元素。如果访问的索引不存在,则会给出未定义的偏移错误。

php
 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
   
// Rohan 
echo $students[0];
  
// ERROR: Undefined offset: 5
echo $students[5];
  
// ERROR: Undefined index: key
echo $students[key];
    
?>


php
 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
   
if(isset($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
    
?>


php
 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
   
if(!empty($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
    
?>


php
 25, 
    "krishna" => 10, 
    "aakash" => 20
); 
  
$index = "aakash"; 
  
print_r(Exists($index, $array)); 
?>


输出:



下面讨论了一些避免未定义偏移错误的方法:

  • isset()函数此函数检查变量是否已设置且不等于 null。它还检查数组或数组键是否具有空值。
    例子:

PHP

 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
   
if(isset($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
    
?>


输出:
Index not present
  • empty()函数该函数检查数组中的变量或索引值是否为空。

PHP

 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
   
if(!empty($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
    
?>


输出:
Index not present
  • 关联数组的array_key_exists()函数关联数组以键值对的形式存储数据,并且对于每个键都存在一个值。 array_key_exists()函数检查指定的键是否存在于数组中。
    例子:

    PHP

     25, 
        "krishna" => 10, 
        "aakash" => 20
    ); 
      
    $index = "aakash"; 
      
    print_r(Exists($index, $array)); 
    ?>
    


    输出:
    Key Found

    PHP是一种专门为 Web 开发设计的服务器端脚本语言。您可以按照此PHP教程和PHP示例从头开始学习PHP 。