Recent Posts

Showing posts with label index. Show all posts
Showing posts with label index. Show all posts

How to solve: Notice: Undefined Index

Happens when you try to access an array by a key that does not exist in the array.
A typical example for an Undefined Index notice would be (demo)
$data = array('foo' => '42', 'bar');
echo $data['spinach'];
echo $data[1];
Both spinach and 1 do not exist in the array, causing an E_NOTICE to be triggered.
The solution is to make sure the index or offset does exist, either by using array_key_exists or isset prior to accessing that index.
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in array';
}