Must I test for Variable Existing as well as its Value?

General discussions related to php

Moderators: macek, egami, gesf

phper2
New php-forum User
New php-forum User
Posts: 3
Joined: Sat Jul 21, 2012 2:36 am

Must I test for Variable Existing as well as its Value?

Postby phper2 » Tue Dec 11, 2012 2:14 am

Hi,

I am wondering if I can have a control structure based just on whether or not a variable has a certain value where there might be times when that variable doesn't exist or whether I need to base it on whether or not the variable actually exists too.

For example can I just have (bearing in mind $var may not exist):

if ($var == 'y')
{
etc.
}

OR

must/should it be:

if (isset($var) && $var == 'y')
{
etc.
}

When testing such a script as the first example on my local-host web server it seems fine even if the variable tested doesn't exist as it just doesn't go into the if code-block but I think I have seen examples of where both are used so am wondering whether some server environments would throw-up errors or cause problems if used the first example when the variable didn't exist at that time.

Thanks for any help in advance.

AM

johnj
php-forum Super User
php-forum Super User
Posts: 1805
Joined: Thu Mar 10, 2011 5:07 pm

Re: Must I test for Variable Existing as well as its Value?

Postby johnj » Tue Dec 11, 2012 5:31 am

To be safe, always use:

Code: Select all

if (isset($var) && $var == 'y')
{

}


Return to “PHP General”

Who is online

Users browsing this forum: No registered users and 1 guest