Home > Article > Backend Development > How to solve undefined index in php
Usually undefined index problems occur because the array does not have this value. Arrays are divided into associative arrays and index arrays. The index array is a numeric subscript; Associative arrays are key-value subscripts.
$POST['id'] reports an undefined index because the $POST array does not contain a value with the subscript key value id. (Recommended learning: PHP video tutorial)
Solution:
Determine whether the array contains a value with the subscript key value id, if If not, an error message will be returned. How to judge? The simplest way is to use the function isset to judge, such as isset($POST['id']). If it exists, it will return true, otherwise it will be false;
The ternary judgment method does not give a default value, such as $POST['id'] = isset($POST['id'])?$POST['id']:"1";
This notification occurs when you (or PHP) try to access an undefined index of an array.
Methods to deal with the problem:
Check whether the index exists before accessing it. You can use isset() or array_key_exists() for this:
//isset()$value = isset($array['my_index']) ? $array['my_index'] : ''; //array_key_exists()$value = array_key_exists('my_index', $array) ? $array['my_index'] : '';
The language construct list() may generate this when trying to access an array index that does not exist:
list($a, $b) = array(0 => 'a');//orlist($one, $two) = explode(',', 'test string');
Two variables for accessing two array elements, but there is only one array element at index 0, so this would generate:
Note: Undefined offset: 1
$_POST/ $ _GET/ $_SESSION variable
When using $_POST, the above considerations often appear, $_GET or $_SESSION.
For your $_POST, $_GET you just need to check if the index exists before using it. Because of $_SESSION you have to make sure to start with session_start() and that the index exists too.
The above is the detailed content of How to solve undefined index in php. For more information, please follow other related articles on the PHP Chinese website!