Wednesday, 29 July 2015

Notice: Undefined Index error in php


This 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 exists prior to accessing that index. This may mean that you need to fix a bug in your program to ensure that those indexes do exist when you expect them to. Or it may mean that you need to test whether the indexes exist using array_key_existsor isset:
$data = array('foo' => '42', 'bar');
if (array_key_exists('spinach', $data)) {
    echo $data['spinach'];
}
else {
    echo 'No key spinach in array';
}
If you have code like:
<?php echo $_POST['message']; ?>
<form method="post" action="">
    <input type="text" name="message">
    ...
then $_POST['message'] will not be set when this page is first loaded and you will get the above error. Only when the form is submitted and this code is run a second time will the array index exist. You typically check for this with:
if ($_POST)  ..  // if the $_POST array is not empty
// or
if ($_SERVER['REQUEST_METHOD'] == 'POST') ..  // page was requested with POST

Share this :

Previous
Next Post »