Search code examples
phplaravelphp-7laravel-5.3

Correct way to avoid `Undefined index` error (NOT NOTICE!!) with php 7


I am not talking about this:

How to avoid undefined index

i am talking about a crash, fatal error. Not about a "notice".

EDIT even if this is caused by a notice, the result is a crash. My question is: how to configure laravel, so it does not crash on notices?

I run laravel 5.3 and php 7.

My error:

ErrorException in UploadController.php line 149:
Undefined index: AS

my code:

 if (!PlumConstants::$plum_us_states[$state]) {
        $state = '';
      }

Referencing my constants class:

    class PlumConstants {
    public static $plum_us_states = array(
        'AL' => 'Alabama',
        'AK' => 'Alaska',
        'AZ' => 'Arizona',
        'AR' => 'Arkansas',
        'CA' => 'California',
//        ...
      );

    }

well, that's a bit funny no? because what I am doing is checking if the entry exists with

 if (!PlumConstants::$plum_us_states[$pstate]) {

but somehow php seems to panic and crash because there was not a defined index... when that is exactly what I am doing and avoiding in my code. Is there a way to switch this odd behavior off? i can probably use isset() but i think it's ugly. Because isset does not mean it is not null or empty. What is the nice way to do this?


Solution

  • If you are using php7 you can do that using

    PlumConstants::$plum_us_states[$pstate] ?? false
    

    instead

    !PlumConstants::$plum_us_states[$pstate]