How to avoid undefined offset error in PHP?

Prior to finding how to keep away from the PHP unclear offset blunder, we should see what it is. The indistinct offset is the one that doesn’t exist inside an exhibit. It is like/learn-php.htmlArrayOutOfBoundException in Java. An endeavor to access such a file will prompt a blunder, which is known as indistinct offset mistake.

There is no such thing as the Offset that in a cluster then it is called as an unclear offset. Indistinct offset mistake is like ArrayOutOfBoundException in Java. Assuming we access a file that doesn’t exist or a vacant offset, it will prompt an indistinct offset mistake.

Model: Following PHP code clarifies how we can get to cluster components. Assuming that the got to record is absent then it gives an unclear offset blunder.

<?php 
   
// Declare and initialize an array
// $students = ['Rohan', 'Arjun', 'Niharika']
$students = array(
    0 => 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
  
// Rohan 
echo $students[0];
 
// ERROR: Undefined offset: 5
echo $students[5];
 
// ERROR: Undefined index: key
echo $students[key];
   
?>

Output:

There are some methods to avoid undefined offset error that are discussed below:

  • isset() function: This function checks whether the variable is set and is not equal to null. It also checks if array or array key has null value or not.
    Example:
<?php 
   
// Declare and initialize an array
// $students = ['Rohan', 'Arjun', 'Niharika']
$students = array(
    0 => 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
  
if(isset($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
   
?>

Output:

Index not present
  • empty() function: This function checks whether the variable or index value in an array is empty or not.
<?php 
   
// Declare and initialize an array
// $students = ['Rohan', 'Arjun', 'Niharika']
$students = array(
    0 => 'Rohan',
    1 => 'Arjun',
    2 => 'Niharika'
);
  
if(!empty($students[5])) {
    echo $students[5];
}
else {
    echo "Index not present";
}
   
?>

Output:

Index not present
  • array_key_exists() function for associative arrays: Associative array stores data in the form of key-value pair and for every key there exists a value. The array_key_exists() function checks whether the specified key is present in the array or not.
    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 = array(
        "ram" => 25, 
        "krishna" => 10, 
        "aakash" => 20
    ); 
     
    $index = "aakash"
     
    print_r(Exists($index, $array)); 
    ?>

    Output:

    Key Four

Also Read: How to use dynamic variable names in JavaScript?

Leave a Reply

Your email address will not be published. Required fields are marked *