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?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With