PHP: printing undefined variables without warning – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and variables . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about 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']
Solution :
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.
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.
echo @$variable;
This is a long-standing issue with PHP, they intend to fix it with isset_or()
(or a similar function) in PHP 6, hopefully that feature will make it into PHP 5.3 as well. For now, you must use the isset()/ternary example in your question, or else use the @ prefix to silence the error. IMHO, this is the only circumstance that justifies using @ in PHP.
I wouldn’t worry about speed issues using echo
with an empty string, it is probably more expensive to wrap it in an if
clause than to just echo empty string.
You can use ?? selector for PHP 7 and later.
echo $variable??'not defined';
undefined variables are very common, i suggest you to initialize variable with null at first
$var = null;
or disable error reporting for notices:
error_reporting(E_ALL^E_NOTICE);
Suppress errors using the @-operator forces the interpreter to change error level, executing the function and then change back error level. This decreases your scripts runtime.
Build a function like this will eliminate at least 3 of your reasons:
function echoVar($var, $ret=NULL) {
return isset($var)?$var:$ret;
}
echoVar($arrayvar['parameter']);
But why echoing undefined variables? This sounds like not really well coded…