Solution to PHP Notice: undefined index or Undefined offset

One of the PHP Notice that we can notice while running PHP Script is Undefined Index or Undefined Offset.

Why PHP Shows the notice – Undefined index or Undefined offset?

Index or offset is associated with array in PHP. If an array variable does not contain key value or the array value is null or empty, then the PHP Notice or warning is going to appear.


We can handle the issue in following way:

Solution 01: Check if the index exists before you access it. For this you can use isset()

$value = isset($array[‘index_num’]) ? $array[‘index_num’] : ”;

Solution 02: Check if the index exists before accessing it using array_key_exists()

$value = array_key_exists(‘my_index’, $array) ? $array[‘my_index’] : ”;

Solution 03: construct list() may generate undefined index or undefined offset when it attempts to access an array index that does not exist:

list($val1, $val2) = array(0 => ‘sekhar’);
list($data1, $data2) = explode(‘,’, ‘string value’);

In the above code, we are using two variables to list the array values but the array contains only one array value. Therefore it will raise, undefined index or offset.

Note: In other case, it may also rise the same PHP Notce: Undefined index or offset and that is while using $_POST,$_GET,$_SESSION global variables. Before using them, we need to check whether the index exists: If(isset($_POST[“index_value”])), if(isset($_GET[“index_value”])), if(isset($_SESSION[“index_value”])). 

Note: While using $_SESSION variable, check session_start() function is called before using session variable. 

Note: Super Global Variables ($_POST,$_GET,$_SESSION) are always in uppercase. So check whether the super global variables are in uppercase.