3

How can you easily avoid getting this error/notice in PHP?

Notice: Undefined index: test in /var/www/page.php on line 21

The code:

$table = 'test';
$preset = array();
method($preset[$table]);

The array $preset exists but not with the specified index

clarkk
  • 27,151
  • 72
  • 200
  • 340
  • Check http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index/16971723#16971723 for IMHO a much better answer I gave in this question – gts Jun 06 '13 at 20:39

3 Answers3

14

Check if it exists using array_key_exists:

$table = 'test';
$preset = array();
if(array_key_exists($table, $preset)) {
    method($preset[$table]);
}else{
    // $table doesn't exist in $preset
}

Alternatively, you could use isset:

$table = 'test';
$preset = array();
if(isset($preset[$table])) {
    method($preset[$table]);
}else{
    // $table doesn't exist in $preset
}
icktoofay
  • 126,289
  • 21
  • 250
  • 231
3

Use if (isset($preset[$table]))

Fabio
  • 18,856
  • 9
  • 82
  • 114
0

Or you can check first if key exists by using isset().

if ( isset($preset[$table]) )

Return true if exists, otherwise return false.

Puzo
  • 596
  • 2
  • 11
  • 26