How to Deal With Undefined Offset Error in PHP
Before discovering how to avoid the PHP undefined offset error, let’s see what it is. The undefined offset is the one that doesn’t exist inside an array. An attempt to access such an index will lead to an error, which is known as undefined offset error.
Let’s see an example:
<?php
// Declare and initialize an array
// $students = ['Ann', 'Jennifer', 'Mary']
$students = [
0 => 'Ann',
1 => 'Jennifer',
2 => 'Mary',
];
// Leyla
echo $students[0];
// ERROR: Undefined offset: 5
echo $students[5];
// ERROR: Undefined index: key
echo $students[key];
?>
Below, we will show you several methods to avoid the undefined offset error.
Using the isset() Function
This function allows checking if the variable is set and is not null.
The example of using the isset function to avoid undefined offset error is as follows:
<?php
// Declare and initialize an array
// $students = ['Ann', 'Jennifer', 'Mary']
$students = [
0 => 'Ann',
1 => 'Jennifer',
2 => 'Mary',
];
if (isset($students[5])) {
echo $students[5];
} else {
echo "Index not present";
}
?>
Index not present
Using the empty() Function
The empty() function is used for checking if the variable or the index value inside an array is empty.
Here is an example:
<?php
// Declare and initialize an array
// $students = ['Rohan', 'Arjun', 'Niharika']
$students = [
0 => 'Ann',
1 => 'Jennifer',
2 => 'Mary',
];
if (!empty($students[5])) {
echo $students[5];
} else {
echo "Index not present";
}
?>
Index not present
Using the array_key_exists() Function
This function is used for associative arrays that store data in the key-value pair form, and there is a value for each key.
The array_key_exists function is used for testing if a particular key exists in an array or not.
Here is an example:
<?php
// PHP program to illustrate the use
// of array_key_exists() function
function Exists($index, $array)
{
if (array_key_exists($index, $array)) {
echo "Key Found";
} else {
echo "Key not Found";
}
}
$array = [
"john" => 25,
"david" => 10,
"jack" => 20,
];
$index = "jack";
print_r(Exists($index, $array));
?>
Key Found