david david - 2 years ago 728
PHP Question

laravel crashes because of undefined index?

recently i've started using laravel. but i am wondering why it crashes and throw exception because of undefined index.

for example:

return $arr1;

this causing the app to crash and return code 500. this is not good at all. i don't need it to crash, it should just return null.

How could i handle this ?

other suggest to wrap each line with isset for example:

return $arr[1]

i can't go through all my code and wrap each line with isset. that's tough work.


Answer Source

You say it's not a code issue, but a Laravel issue..... it is a code issue, PHP issues a notice if you try to access an array element that doesn't exist.... you may choose to suppress that notice, or (as Laravel does) to report it in a clean fashion; but it is not a PHP issue, or a Laravel issue; it is a response to sloppy coding. If it runs without issue outside of Laravel, then that's because you're suppressing notices, not because it isn't an issue.

If you want a null return if you try to access an undefined index in an array, then I'd suggest creating a custom error handler to trap for that.

function myErrorHandler($errno, $errstr, $errfile, $errline) {
    if ($errno == E_NOTICE && strpos($errstr, 'Undefined offset') === 0) {
        return null;
    return false;

$old_error_handler = set_error_handler("myErrorHandler");



Of course, you'd have to integrate that logic with Laravel's own error handling routines


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download