What is the proper way to do an if/else statement regarding a variable which may or may not exist?
For example: I have a website search script that gets variables from the URL. If the user has not checked any advanced options then they are not included in the URL. Basically what I'm wondering is, would it be correct to use something like the following if the variable did not exist?
if ($variable == "yes") { do stuff; }
Would this cause any sort of problems if that variable did not exist? or should I always use something like:
if (isset($variable) && $variable == "yes") { do stuff; }
The second way imo, because it will suppress the notice error that $variable does not exist if it's not set. Either way, it's only a notice error though - so you could just suppress notices and use the first way too..
try to put the if value equals in the if statement, this way you never get error notice and its correct
if(isset($value)){
if($value==='this'){
//magic
}
}
Before you check your variable for a value, check it with isset and set default values like
if (!isset($variable)) {
$variable = "no";
}
if ($variable == "yes") { do stuff; }
No warning is generated if the variable does not exist. That means empty()
is essentially the concise equivalent to !isset($var) || $var == false
.
// $foo = 'no';
if(!empty($foo) AND $foo == 'yes')
{
echo $foo;
}