Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch undefined index in array and create it

Tags:

arrays

php

<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 (database lookup) & return it from my function and then perform echo ?

like image 570
MotionGrafika Avatar asked Dec 29 '22 09:12

MotionGrafika


2 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'];
like image 66
jkilbride Avatar answered Jan 08 '23 06:01

jkilbride


You can check if this particular index exists before you access it. See the manual on isset(). It's a bit clumsy as you have to write the variable name twice.

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

You might also consider changing the error_reporting value for your production environment.

like image 42
svens Avatar answered Jan 08 '23 07:01

svens