Search code examples
phpexceptionsymfonyerror-handlingdry

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?


Solution

  • 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.