5

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?

Enrique Moreno Tent
  • 24,127
  • 34
  • 104
  • 189
  • How about checking `if(isset($test["323"]))`? – geomagas Oct 31 '13 at 10:28
  • This is a PHP issue, not a Symfony one: [see here](http://stackoverflow.com/search?q=php+undefined+index). – halfer Oct 31 '13 at 10:32
  • possible duplicate of [Undefined index (PHP)](http://stackoverflow.com/questions/14813550/undefined-index-php) – halfer Oct 31 '13 at 10:32
  • +1 for question as it is very annoying to have extra code testing variable set eg. when using `??` or similar as fallback already. Using [@ for suppressing notice](https://www.php.net/manual/en/language.operators.errorcontrol.php) logged to Symfony logger wasn't working in my case either. According to PHP doc @ isn't suppressing custom error handler being called. As stated in note on linked page this is up to that custom handler to obey individual suppression. Thus it is more related to Symfony than to PHP ... eventually this question is not a duplicate of linked thread either. – Thomas Urban Aug 16 '20 at 14:49

6 Answers6

14

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;
Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
8

An option would be to use set_error_handler() in order to, somehow, simulate exceptions. An example usage would be the following, although I'm sure you can adjust this to your specific use case:

function my_error_handler($errno,$errstr)
  {
  /* handle the issue */
  return true; // if you want to bypass php's default handler
  }

$test = array();
set_error_handler('my_error_handler');
$use_it=$test["323"]; // Undefined index error!
restore_error_handler();

You can see that we "wrap" our "critical" piece of code around set_error_handler() and restore_error_handler(). The code in question can be as little as a line, to as large as your whole script. Of course, the larger the critical section, the more "intelligent" the error handler has to be.

geomagas
  • 3,230
  • 1
  • 17
  • 27
  • This look much more like what I wanted! But I would like to know how to handle the issue... – Enrique Moreno Tent Oct 31 '13 at 11:24
  • @Dbugger: Well, I guess that would depend on the application logic. What would you like to happen in a situation like this? My guess is that you'd want some custom failover (plan-B) procedure to take over and sort things out. – geomagas Oct 31 '13 at 11:51
  • Oh, you mean that what is inside of "my_error_handler" is the equivalent to the "catch" block? I thought it would be where the "throw" is executed. Could you please show me an example, with whatever error handling you prefer? Also, how does this error_handler play with, when inside a try-catch block? – Enrique Moreno Tent Oct 31 '13 at 12:40
  • I think the link I provided has better examples that I could possibly provide here. There's also a good explanation of how these functions work and what other parameters can be passed. – geomagas Oct 31 '13 at 12:45
3

use array_key_exists(), like

if (array_key_exists('123', $test)) {
    echo "it exists";
}
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
0

You can catch this bx surrounding it with isset: if(isset($test["323"])){ //The value fo this key is set. }

0

May be you wanted to achieve this ?

$test = array();
$test[]="323";

echo $test[0];//323 
Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
0

Simple way to try/catch undefined or many php errors.

try{
    set_error_handler(function($errno, $errstr, $errfile, $errline, array $errcontext){
       if (0 === error_reporting()) { return false; }
       throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
    });
    
    $data = $json['name']; ---> Undefined Index name
}catch(Exception $e){
    //Perform Furthur action 
}
somsgod
  • 357
  • 2
  • 11