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?

4
  • How about checking if(isset($test["323"]))? Commented Oct 31, 2013 at 10:28
  • This is a PHP issue, not a Symfony one: see here. Commented Oct 31, 2013 at 10:32
  • possible duplicate of Undefined index (PHP) Commented Oct 31, 2013 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 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. Commented Aug 16, 2020 at 14:49

6 Answers 6

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;
Sign up to request clarification or add additional context in comments.

4 Comments

@Dbugger Most of the time, you should know what is in your array.
But if I am loading a yaml or INI file, which my customer can customize, it could break stuff. Still not the point of the question
@Dbugger On page load, would you not load the ini file via a loop? And have defaults for each setting, in case they don't exist in the ini file?
Possible solution, but might not work for every case
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.

4 Comments

This look much more like what I wanted! But I would like to know how to handle the issue...
@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.
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?
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.
3

use array_key_exists(), like

if (array_key_exists('123', $test)) {
    echo "it exists";
}

Comments

0

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

Comments

0

May be you wanted to achieve this ?

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

echo $test[0];//323 

Comments

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 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.