Catch an undefined index in an array and create it

<h1><?php echo $GLOBALS['translate']['About'] ?></h1> Notice: Undefined index: About in page.html on line 19 

Is it possible to "catch" an undefined index so that I can create it (search the database) and return it from my function and then perform an echo?

+4
source share
6 answers

The easiest way to check if a value has been assigned is to use the isset method:

 if(!isset($GLOBALS['translate']['About'])) { $GLOBALS['translate']['About'] = "Assigned"; } echo $GLOBALS['translate']['About']; 
+7
source

You can check if this particular index exists before it is accessed. See the isset() manual. This is a bit awkward since you need to spell the variable name twice.

 if( isset($GLOBALS['translate']['About']) ) echo $GLOBALS['translate']['About']; 

You might also want to change the error_reporting value for your production environment.

+2
source

that would be wrong. I would make an effort to build the array correctly. otherwise, you can get 1000 dB of requests per page.

also you should check the array before exiting and maybe put it by default:

 <h1><?php echo isset($GLOBALS['translate']['About'])?$GLOBALS['translate']['About']:'default'; ?></h1> 
+1
source

Yes. Use isset to determine if an index is defined, and then if it is not, you can assign a value to it.

 if(!isset($GLOBALS['translate']['About'])) { $GLOBALS['translate']['About'] = 'foo'; } echo "<h1>" . $GLOBALS['translate']['About'] . "</h1>"; 
0
source

try something like:

 if ( !isset($GLOBALS['translate']['About']) ) { $GLOBALS['translate']['About'] = get_the_data('About'); } echo $GLOBALS['translate']['About']; 
0
source

You need to define your own error handler if you want to catch the Undefined index

 set_error_handler('exceptions_error_handler'); function exceptions_error_handler($severity, $message, $filename, $lineno) { if (error_reporting() == 0) { return; } if (error_reporting() & $severity) { throw new ErrorException($message, 0, $severity, $filename, $lineno); } } try{ }catch(Exception $e){ echo "message error"; } 
0
source

Source: https://habr.com/ru/post/1316402/


All Articles