php: undefined offset and undefined index

by prettyscripts on 2010-02-11 10:36:45

php

sometimes the following notice is displayed when accessing array:

PHP Notice: Undefined offset [number] in /path/to/your/file.php on line [number]

or this:

PHP Notice: Undefined index [number] in /path/to/your/file.php on line [number]

this means the array key / index does not exist in the array.

it's worthwhile to check with print_r() to see what's in the array.

usually errors at notice level have no major impact to the functionality of the code. it can be turned off with error_reporting() (recommend for production):

error reporting(E_ALL & ~E_NOTICE);

however it's better not to turn this off at development level and try to fix it. check if the key exists with isset(). if using list() with explode() for string that may return variable array size:

@list($var1, $var2, $var3) = explode(':', $string);

Tags: notice, php, undefined

No feedback yet

Leave a comment


Your email address will not be revealed on this site.
PoorExcellent
note: all comments are moderated. do not spam and do not advertise. only comments relevant to the post will be published.
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)