PHP Basics

What is the efficient way to fix notice undefined offset array index in PHP?

Array datatype in php contains different values and these values are fetched using index number. Often dealing with array, we encounter undefined offset.

What causes undefined offset notice?

Lets understand with the help of an example.

Example

<?php

$fruits=array(“apple”,”orange”,”grape”, “guava”,”mango”);

?>

 

In the above example, $fruits array contains fruit names.

If I want to get the first fruitname, then I have to provide the index number 0.

<?php

echo $fruits[0];

?>

output: apple

In similar fashion, I have to print rest fruit names then I have to provide its respective index number

<?php

$fruits=array(“apple”,”orange”,”grape”, “guava”,”mango”);

echo $fruits[1].'<br/>’;

echo $fruits[2].'<br/>’;

echo $fruits[3].'<br/>’;

echo $fruits[4].'<br/>’;

?>

Output:

orange

grape

guava

mango

Now, what will happen if I print $fruits[5] ?

It will show: Notice: Undefined offset: 5 in C:\xampp\htdocs\gyanol\test.php on line 3

 

Why did this notice appear?

Because the array fruits has only five elements. So the maximum index number would be 4. In this case, I have provided 5. So it showed error.

Therefore, when ever we get notice: undefined offset, it means the provided index number is larger than the maximum index number in the array.

Notice: Undefined offset solution

We can handle undefined offset notice in multiple ways.

Solution 1

Check if the provided index number is not larger than the maximum index number of the array.

Example

<?php

$fruits=array(“apple”,”orange”,”grape”, “guava”,”mango”);

if(5 < sizeOf($fruits)-1){

echo $fruits[5];

}

?>

 

Solution 2

Using predefined php function array key exists() array_key_exists()

Example

<?php

$fruits=array(“apple”,”orange”,”grape”, “guava”,”mango”);

if(array_key_exists($fruits,5)){

echo $fruits[5];

}

?>

 

The both solutions in the above going to work and help to overcome the notice undefined offset. The goal is to first check whether the index number that we are providing to get data is valid or not. If it is valid then it will show the data otherwise will throw error.