Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: printing undefined variables without warning

I'm just wondering if there is a quick way to echo undefined variables without getting a warning? (I can change error reporting level but I don't want to.) The smallest I have so far is:

isset($variable)?$variable:''

I dislike this for a few reasons:

  • It's a bit "wordy" and complex
  • $variable is repeated
  • The echoing of a blank string always kind of annoys me.
  • My variable names will probably be longer, eg $arrayvar['parameter']
like image 626
DisgruntledGoat Avatar asked Nov 27 '22 16:11

DisgruntledGoat


2 Answers

You can run it with the error suppression operator @.

echo @$variable;

However, it's best not to ignore unset variables. Unset variables could indicate a logical error on the script, and it's best to ensure all variables are set before use.

like image 118
Eran Galperin Avatar answered Dec 09 '22 13:12

Eran Galperin


you could use the ifsetor() example taken from here:

function ifsetor(&$variable, $default = null) {
    if (isset($variable)) {
        $tmp = $variable;
    } else {
        $tmp = $default;
    }
    return $tmp;
}

for example:

echo ifsetor($variable);
echo ifsetor($variable, 'default');

This does not generate a notice because the variable is passed by reference.

like image 42
Tom Haigh Avatar answered Dec 09 '22 14:12

Tom Haigh