[Solved] Notice: Undefined index error in PHP
  John Mwaniki /   11 Dec 2021

[Solved] Notice: Undefined index error in PHP

When working with arrays in PHP, you are likely to encounter "Notice: Undefined index" errors from time to time.

In this article, we look into what these errors are, why they happen, the scenarios in which they mostly happen, and how to fix them.

Let's first look at some examples below.

Examples with no errors

Example 1

<?php
$person = array("first_name" => "John", "last_name" => "Doe");
echo "The first name is ".$person["first_name"];
echo "<br>";
echo "The last name is ".$person["last_name"];

Output:

The first name is John
The last name is Doe

Example 2

<?php
$students = ["Peter", "Mary", "Niklaus", "Amina"];
echo "Our 4 students include: <br>";
echo $students[0]."<br>";
echo $students[1]."<br>";
echo $students[2]."<br>";
echo $students[3];

Output:

Our 4 students include:
Peter
Mary
Niklaus
Amina

Examples with errors

Example 1

<?php
$employee = array("first_name" => "John", "last_name" => "Doe");
echo $employee["age"];

Output:

Notice: Undefined index: age in /path/to/file/filename.php on line 3

Example 2

<?php
$devs = ["Mary", "Niklaus", "Rancho"];
echo $devs[3];

Output:

Notice: Undefined offset: 3 in /path/to/file/filename.php on line 3

Let's now examine why the first two examples worked well without errors while the last two gave the "Undefined index" error.

The reason why the last examples give an error is that we are attempting to access indices/elements within an array that are not defined (set). This raises a notice.

For instance, in our $employee array, we have only defined the "first_name" element whose value is "John", and "last_name" element with the value "Doe" but trying to access an element "age" that has not been set in the array.

In our other example with the error, we have created an indexed array namely $devs with 3 elements in it. For this type of array, we use indices to access its elements. These indices start from zero [0], so in this case, Mary has index 0, Niklaus has index 1, and Rancho index 2. But we tried to access/print index 3 which does not exist (is not defined) in the array.

On the other hand, you will notice that in our first two examples that had no errors, we only accessed array elements (either through their keys or indices) that existed in the array.

The Solutions

1. Access only the array elements that are defined

Since the error is caused by attempting to access or use array elements that are not defined/set in the array, the solution is to review your code and ensure you only use elements that exist in the array.

If you are not sure which elements are in the array, you can print them using the var_dump() or print_r() functions.

Example

<?php
//Example 1
$user = array("first_name" => "John", "last_name" => "Doe", "email" => "johndoe@gmail.com");
var_dump($user);

//Example 2
$cars = array("Toyota","Tesla","Nisan","Bently","Mazda","Audi");
print_r($cars);

Output 1:

array(3) { ["first_name"]=> string(4) "John" ["last_name"]=> string(3) "Doe" ["email"]=> string(17) "johndoe@gmail.com" }

Output 2:

Array ( [0] => Toyota [1] => Tesla [2] => Nisan [3] => Bently [4] => Mazda [5] => Audi )

This way, you will be able to know exactly which elements are defined in the array and only use them.

In the case of indexed arrays, you can know which array elements exist even without having to print the array. All you need to do is know the array size. Since the array indices start at zero (0) the last element of the array will have an index of the array size subtract 1.

To get the size of an array in PHP, you use either the count() or sizeof() functions.

Example

<?php
$cars = array("Toyota","Tesla","Nisan","Bently","Mazda","Audi");

echo count($cars);  //Output: 6
echo "<br>";
echo sizeof($cars);  //Output: 6

Note: Though the size of the array is 6, the index of the last element in the array is 5 and not 6. The indices in this array include 0, 1, 2, 3, 4, and 5 which makes a total of 6.

If an element does not exist in the array but you still want to use it, then you should first add it to the array before trying to use it.

2. Use the isset() php function for validation

If you are not sure whether an element exists in the array but you want to use it, you can first validate it using the in-built PHP isset() function to check whether it exists. This way, you will be sure whether it exists, and only use it then.

The isset() returns true if the element exists and false if otherwise.

Example 1

<?php
$employee = array("first_name" => "John", "last_name" => "Doe");

if(isset($employee["first_name"])){
  echo "First name is ".$employee["first_name"];
}

if(isset($employee["age"])){
  echo $employee["age"];
}

First name is John

Though no element exists with a key "age" in the array, this time the notice error never occurred. This is because we set a condition to use (print) it only if it exists. Since the isset() function found it doesn't exist, then we never attempted to use it.

Scenarios where this error mostly occur

The "Notice: Undefined index" is known to occur mostly when using the GET and POST requests.

The GET Request

Let's say you have a file with this URL: https://www.example.com/register.php.

Some data can be passed over the URL as parameters, which are in turn retrieved and used in the register.php file.

That URL, with parameters, will look like https://www.example.com/register.php?fname=John&lname=Doe&age=30

In the register.php file, we can then collect the passed information as shown below.

<?php
$firstname = $_GET["fname"];
$lastname = $_GET["lname"];
$age = $_GET["age"];

We can use the above data in whichever way we want (eg. saving in the database, displaying it on the page, etc) without any error.

But if in the same file we try accessing or using a GET element that is not part of the parameters passed over the URL, let's say "email", then we will get an error.

Example

<?php
echo $_GET["email"];

Output:

Notice: Undefined index: email in /path/to/file/filename.php on line 2

Solution

Note: GET request is an array. The name of the GET array is $_GET. Use the var_dump() or print_r() functions to print the GET array and see all its elements.

Like in our register.php example with URL parameters above, add the line below to your code:

<?php
var_dump($_GET);

Output:

array(3) { ["fname"]=> string(4) "John" ["lname"]=> string(3) "Doe" ["age"]=> string(2) "30" }

Now that you know which elements exist in the $_GET array, only use them in your program.

As in the solutions above, you can use the isset() function just in case the element doesn't get passed as a URL parameter.

In such a scenario you can first initialize all the variables to some default value such as a blank, then assign them to a real value if they are set. This will prevent the "Undefined index" error from ever happening.

Example

<?php
$firstname = $lastname = $email = $age = "";

if(isset($_GET["fname"])){
  $firstname = $_GET["fname"];
}
if(isset($_GET["lname"])){
  $lastname = $_GET["lname"];
}
if(isset($_GET["email"])){
  $email = $_GET["email"];
}
if(isset($_GET["age"])){
  $age = $_GET["age"];
}

The POST Request

The POST request is mainly used to retrieve the submitted form data.

If you are experiencing the "Undefined index" error with form submission post requests, the most probable cause is that you are trying to access or use post data that is not being sent by the form.

For instance, trying to use $_POST["email"] in your PHP script while the form sending the data has no input field with the name "email" will result in this error.

The easiest solution for this is to first print the $_POST array to find out which data is being sent. Then you review your HTML form code to ensure that it contains all the input fields which you would want to access and use in the PHP script. Make sure that the value of the name attributes of the form input matches the array keys you are using in the $_POST[] of your PHP.

In a similar way to the solution we have covered on GET requests on using the isset() function to validate if the array elements are set, do it for POST.

You can in a similar way initialize the values of the variables to a default value (eg. blank), then assign them the real values if they are set.

<?php
$firstname = $lastname = $email = $age = "";

if(isset($_POST["fname"])){
  $firstname = $_POST["fname"];
}
if(isset($_GET["lname"])){
  $lastname = $_POST["lname"];
}
if(isset($_GET["email"])){
  $email = $_POST["email"];
}
if(isset($_POST["age"])){
  $age = $_POST["age"];
}

If the HTML form and the PHP code processing the file are in the same file, then ensure that the form processing code doesn't get executed before the form is submitted.

You can achieve this by wrapping all the processing code in a condition that checks if the form has even been sent as below.

<
if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
/*
 Write code to process your form here
*/
}
else{
/*
 Do nothing... Just show the HTML form
*/
}

That's all for this article. It's my hope it has helped you.