Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling "Undefined Index" in PHP with SYmfony

I am building an app with Symfony 2, and I am wondering, how could I handle errors when I try to read a index in an array that doesn't exist? Sadly this kind of errors don't throw exceptions, so I can't really use a try-catch block.

Example:

$test = array();
$test["323"];       // Undefined index error!

Please, ideas how to handle this errors?

Update: I have seen many solutions with isset. The problem with this is that I would have to do it with every single access to an array index. Can anyone offer me a more DRY solution?

like image 273
Enrique Moreno Tent Avatar asked Nov 28 '22 07:11

Enrique Moreno Tent


1 Answers

Both:

if(isset($test["323"])){
   //Good
}

and

if(array_key_exists('123', $test)){
   //Good
}

Will allow you to check if an array index is defined before attempting to use it. This is not a Symfony-specific error. Its a common PHP warning that occurs whenever you attempt to access an array element that doesn't exist.

$val = isset($test["323"]) ? $test["323"] : null;
like image 121
Wayne Whitty Avatar answered Nov 30 '22 19:11

Wayne Whitty