4
<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 ?

6 Answers 6

7

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

Comments

2

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.

Comments

1

that wouldn't be the right thing to do. i would put effort into building the array properly. otherwise you can end up with 1000 db requests per page.

also, you should check the array before output, and maybe put a default value there:

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

Comments

0

try something like:

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

Comments

0

Yes. Use isset to determine if the index is defined and then, if it isn't, you can assign it a value.

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

2 Comments

this is a very sloppy post: a spurious ), missing ;, missing open/close tags...
Whooops... that was indeed pretty bad. Thanks for the catch.
0

You need to define your custom error handler if you want to catch 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";
}

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.