Echoing things that don't exist

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Echoing things that don't exist

Post 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_?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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

Code: Select all

error_reporting(E_ALL);
To answer your question, yes. If a variable is not guaranteed to exist you should always check.
User avatar
Chalks
Forum Contributor
Posts: 447
Joined: Thu Jul 12, 2007 7:55 am
Location: Indiana

Post by Chalks »

whoops, didn't realize I hadn't turned on error reporting. Thanks Jcart.
User avatar
s.dot
Tranquility In Moderation
Posts: 5001
Joined: Sun Feb 06, 2005 7:18 pm
Location: Indiana

Post 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;
}
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
Post Reply