Page 1 of 1
Echoing things that don't exist
Posted: Sun Dec 16, 2007 1:50 pm
by Chalks
I know that if I put
Code: Select all
echo $_SESSION['aonidii2lk333']; // no, this variable name does not exist
my script won't explode. I don't even get any errors. However, I'm not sure having references to nonexistant variables is good coding practice. Should I check to see if it exists before I echo it _no matter what_?
Posted: Sun Dec 16, 2007 1:58 pm
by John Cartwright
Using variables that do not exist will fire notices. You probably aren't seeing the notices because your error reporting is set too low. You should always be coding with
To answer your question, yes. If a variable is not guaranteed to exist you should always check.
Posted: Sun Dec 16, 2007 2:34 pm
by Chalks
whoops, didn't realize I hadn't turned on error reporting. Thanks Jcart.
Posted: Sun Dec 16, 2007 2:44 pm
by s.dot
Yes, always check if a variable (or array key) exists. Always instantiate variables that you are going to use.
Code: Select all
//bad
while ($something)
{
$string .= $foo;
}
//good
$string = '';
while ($something)
{
$string .= $foo;
}
//bad
while ($something)
{
$array[] = $foo;
}
//good
$array = array();
while ($something)
{
$array[] = $foo;
}