Forum Moderators: coopster
I currently have this line:
<?php echo $variable; ?>
But $variable is not always set. When it isnt set, nothing is outputted, no errors etc, so nothing is technically wrong.
However, I'm wondering if theres a more correct way of going about outputting this variable in terms of better code, better practise, (quicker perhaps?) etc..
Is this a more suitable option, despite been slightly more code (if thats of any concern)?
<?php if (isset ($variable)) echo $variable; ?>
Or is there another/better way of going about it?
thanks
:)
no errors etc, so nothing is technically wrongIt is technically wrong; you're generating a notice which you apparently are not seeing because of your error level. Use error_reporting() [us3.php.net] to change it. When you're developing/debugging a script of any complexity, you should set it to E_ALL. Then when you're finished, set it to 0.
if(isset($variable)) is fine, and whether that or something else is the end solution is script/app dependent. In many cases your script's flow should ensure that you don't reach a condition wherein you're trying to report something that's not there. isset(), mysql_num_rows(), in_array() and a host of others are used to make those flow decisions, and I would say that in general it's "better" that decisions are made quite a bit higher up than when you're starting to echo your content. For example, if the script tried to retrieve a database record that wasn't found and $variable isn't set as a consequence of that failure, you should have gone down a different path to report or handle the absence of the data long before you got around to echoing stuff. In other applications, $variable not being defined may be a nonissue, so isset() right at the echo is all you need.
It is technically wrong; you're generating a notice which you apparently are not seeing because of your error level. Use error_reporting() to change it. When you're developing/debugging a script of any complexity, you should set it to E_ALL. Then when you're finished, set it to 0.
Thanks. Very useful info :)
I would presume the error level is set quite low on the server (both locally and the live server).
I will use the E-ALL error reporting in the future.
:)
If the warning matters to you, the most efficient way to avoid it is with $variable = ''; at the beginning of the script.
Note that it can be argued that uninitialized variable warnings in PHP are completely irrelevant and can be ignored.