What is undefined index Notice in PHP array process and How to avoid it?

Undefined index Notice in PHP array processing. When we try to access key in PHP array which not exists in array, PHP gives Undefined index Notice.

What is undefined index Notice in PHP?

In PHP when code syntax try to access array element using key, which not exist in array, PHP display Undefined index Notice.

Undefined index Notice in PHP

How to avoid undefined index Notice in PHP?

As we check reason for notice, now here is solution for avoid such undefined index notice.

In code syntax use isset or empty PHP function before access array element using key.

Let’s see example how to use isset or empty function for avoid undefined index notice.

Normal code which gives notice

$arr = array(
    'first' : 'firstEle',
    'second' : 'secondEle',
    'third' : 'thirdEle',
);

$key = 'four';

//CASE 1:
if ($arr[$key]) {
    //some code
}

//CASE 2:
$var = $arr[$key];

safe code which avoid notice

$arr = array(
    'first' : 'firstEle',
    'second' : 'secondEle',
    'third' : 'thirdEle',
);

$key = 'four';

//CASE 1:
if (isset($arr[$key]) && $arr[$key]) {
    //some code
}

if (!empty($arr[$key])) {
    //some code
}

//CASE 2:
$var = !empty($arr[$key]) ? $arr[$key] : 'some default value';
$var = $arr[$key] ?? 'some default value';