If($var) vs. if(isset($var))

Hi,

When checking whether the submit button is pressed or not,

if I use

if (isset($_POST['submit']))

it works fine. If I use

if ($_POST['submit'])

it gives an “Undefined index” notice, which means I need isset() for this check.

When checking whether the username and password fields are empty or not, both of the following works fine.

if (isset($_POST['username']) && isset($_POST['password']))
if ($_POST['username'] && $_POST['password'])

which means I don’t need isset() for this check.

My question is, should I always use isset() for checking variables or is it ok not to use it where it is not required?

[fphp]isset/fphp doesn’t check against empty, rather it checks whether or not the variable is set (or array index/key is set).

To test against empty, you really should use [fphp]empty/fphp

if($var)

If $var is 0; this is false.
If $var is “false”, this is true.

Proper coding should never use if($var). if(!isset($var)), if(empty($var)), if ($var === FALSE)…

Now, as to your specific query, as cpradio has said, isset doesnt check for emptyness.

Text Fields in a form are -ALWAYS- sent, even if they contain nothing.
Thus, the variable $_POST[‘username’] will always be set when the form is submitted, but may contain nothing.

IIRC, this will only work if the user submitted the form by pressing the Submit button (although only an IE peculiarity I think).

A user can submit a form by just pressing Enter on the keyboard so therefore you cannot be guaranteed the form submission will be caught.

I find there is usually a form element which must always contain something, an email address field maybe.

I generally enforce that this does at least contain something on the client, but of course js can be turned off.


if( !strlen($_POST['email']) ){
// a check like this can work as confirmation that the
// form was not submitted or at least a key element 
// was missed, so you cannot continue, so tell the user
// fail here
}

// otherwise presume the form was indeed submitted

What do others think of this method?

Thanks, I will be using empty() from now on.

I am not sure if I clearly understood your example. The following two code blocks have the same output (bad):

<?php
$var = 0;
if ($var) {
	echo 'good';
} else {
	echo 'bad';
}
?>
<?php
$var = FALSE;
if ($var) {
	echo 'good';
} else {
	echo 'bad';
}
?>

Thanks for the suggestion, I am just trying to learn the real "why"s so that I will not just copy & paste code from here or there but I will know the reasoning behind it.

Sorry, what does IIRC mean? I tried submitting the form by pressing enter on all browsers and it worked as it should. Maybe it is an issue with previous IE versions?

Was this meant to say never use if($var), but instead use isset, empty, === or !==? Just curious, as I first read it as never use if($var) or !isset(), empty(), or === FALSE and I mentally went WTF? Never heard that before… maybe I misread it.

That is a conflict between FALSE and “FALSE” (being a string). The point is, your condition will be glitchy because of the automatic type conversion PHP runs on your variables. That is why it is recommended to use isset(), empty(), and identical comparison (=== or !==)

I strongly encourage looking at the tables on http://www.php.net/manual/en/types.comparisons.php
It will help show you how using a loose comparison could skew your expectations (same with using if($x)).

<?php
$var = 0;
if ($var) { // should echo "bad"
	echo 'good';
} else {
	echo 'bad';
}
?>
<?php
$var = "FALSE";
if ($var) { // should echo "good"
	echo 'good';
} else {
	echo 'bad';
}
?>

Thanks a lot, I will read it. I know that logical FALSE and string “FALSE” are two different things but I agree with your point.

This is why punctuation is important. :wink: Note the . after the first statement, and the ,'s following. It’s meant to read as never use if($var). Instead use …

I strongly encourage looking at the tables on http://www.php.net/manual/en/types.comparisons.php
It will help show you how using a loose comparison could skew your expectations (same with using if($x)).

http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting also a good read for IF’s.

Off Topic:

That’s exactly why I had to re-read it; I was certain that couldn’t be what you were implying :slight_smile:

If I Recall Correctly, which possibly I have not :wink:

Anyhow, checking for the existence of ‘submit’ is a habit I got out of using. Have I been mistaken all this time I wonder? …

Not mistaken, maybe just a bit of over-exaggerated? http://www.dev-archive.net/articles/forms/multiple-submit-buttons.html

Looks like the issue primarily pertains to using the button element for submitting a form instead of input with a type of submit.

Yes, in typical fashion I probably pruned much of the detail away in my mind and ended up with a shorthand version stuck away in a dusty cupboard in my brain. Don’t rely on ‘submit’.

What’s wrong with if($var)? It’s a very nice shorthand and a very convenient one provided you are aware how it functions.

if($var) is equivalent to if (!empty($var))
if(!$var) is equivalent to if (empty($var))

the only difference being that empty() will not issue notice errors in $var is not set. For exampe:


// get array of products
$var = getProducts();

if ($var) {
  // ...
}

This is an easy check whether $var array has any elements. In the same way, you can check whether a function/method returned an object as expected or null/false. Less typing and very convenient.

It’s only important to be cautious about using if($var) on strings and numbers.

For checking if a form text field has been filled in this is good:


if (isset($_POST['var']) && is_string($_POST['var']) && $_POST['var'] !== '')

Apart from the possibilities of getting results that were not expected, I find that using if ($var) is much harder to test. If you take a look at the link I posted back earlier, your tests would need to take into account all of the rows in the table.

By explicitly saying isset(), is_string(), and !== ‘’, you now know exactly what you need to test against and your readability just went up.

  1. If you just need to check whether the page was opened via GET or POST method (clicking a link vs submitting a form) use this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// process form
}
  1. isset() is not used to check the emptiness of a variable. It checks for the presence of a variable in the PHP symbol table. The presence of variable does not imply the variable contains a meaningful value. If the user submitted an EMPTY form then:
if (isset($_POST['username']) && isset($_POST['password'])) // CONDITION PASSES SINCE BOTH VARIABLES ARE SET (BOTH CONTAIN EMPTY STRING OF COURSE)
if ($_POST['username'] && $_POST['password']) // CONDITION FAILS BUT NOTICE IS NOT ISSUED
  1. Now the recommended solution: use empty() function:
if (! empty($_POST['username']) && ! empty($_POST['password'])) 
// 1) NOTICE IS NOT ISSUED IF THE VARIABLE IS NOT PRESENT (see empty() documentation)
// 2) BOTH VARIABLES MUST BE NON-EMPTY (0, "", NULL, false etc are considered empty)

Not to mention that what production site are you working on that wants PHP E_NOTICE’s thrown into their page?

I use something like this to check:
if (isset($_POST[‘var’]) && is_string($_POST[‘var’]) && $_POST[‘var’] !== ‘’) {

}

I thought all POST values were strings, so a check for is_string() seems superfluous to me.

If an empty string ‘’ is a fail, I’d guess a space in a string would be just as useless ’ '.

A combination of a boolean check of strlen() and trim() be a bit more useful.


$_POST['var'] = " 3 ";

if (isset($_POST['var']) && strlen(trim($_POST['var']))) {
//....
echo "var at least contained something other that a space ..." ;

}

Occasionally though, you may want to run trim() again on a number of POST vars before say, storing in a db table, so given the same incoming you could use :


$_POST['var'] = " 3 ";

var_dump($_POST['var']);  // string (3) ' 3 '

$_POST = array_map( 'trim', $_POST);
// now all your POST vars have been trimmed ...


// now just check exists, and strlen is not 0
if (isset($_POST['var']) && strlen($_POST['var'])) {
//....
echo "var at least contained something other that a space ..." ;
var_dump($_POST['var']); // string (1) '3'

}

No! POST and GET values can also be arrays - when the input names contain square brackets - so is_string() is a very desirable validation check. I wouldn’t want to run strlen() on an array or do any other string manipulations on a $var before knowing it is a string.

Thanks for correcting me then.