Home > front end >  Best way to handle Undefined array key in PHP 8.0
Best way to handle Undefined array key in PHP 8.0

Time:01-02

I upgraded to PHP 8.0 a few months ago and like a lot of developers I'm having trouble with this notice turned into a warning. I don't understand the proper way to deal with this so I'd like to know how to fix this without bloating my code.

Previously I would do this

public function myFunction($options = []){

    //we know $options is an array, so let's check if the key is there and get its value at the same time
    if($run = $options['run']){ 
            
        //do something with $run
            
    }
}

$options is initialized as an array and if key 'run' is defined I get its value ready to be used. What it's being suggested I handle with this simple piece of code now is...

public function myFunction($options = false){

    if(isset($options['run']){

        $run = $options['run'];
            
        //do something with $run
            
    }
}

It seems to me like this is adding an extra unneeded step: is it really how it should be handled?

Thanks in advance

CodePudding user response:

You can do this to avoid typical if/else block

$run = $options['run'] ?? null;

To know more details https://wiki.php.net/rfc/isset_ternary

CodePudding user response:

You can suppress the error by appending "@" before the expression. $run will be null if the key doesn't exists:

if($run = @$options['run']){ 
    //do something with $run   
}
  • Related