Handling "Undefined Index" in PHP with SYmfony Handling "Undefined Index" in PHP with SYmfony symfony symfony

Handling "Undefined Index" in PHP with SYmfony


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;


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.


use array_key_exists(), like

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