isset vs. empty

Sat, Jan 9, 2010

PHP

Many people tend to view these two functions as opposites, causing necessary debugging. This issue frequently occurs when validating forms.

isset()

From the PHP manual:

isset — Determine if a variable is set and is not NULL

In other words, a variable is set if it has been assigned a value other than NULL. If a variable is assigned to be an empty string – it is set. The following code and output should illustrate my point.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php

var_dump(isset($x));

$x = NULL;
var_dump(isset($x));

$x = "";
var_dump(isset($x));

$x = '';
var_dump(isset($x));

?>
bool(false)
bool(false)
bool(true)
bool(true)

empty()

Again from the PHP manual:

empty — Determine whether a variable is empty

In other words, a variable is empty if it is an empty string, 0, “0″, false, NULL, array(), and an unset variable are all empty.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php

var_dump(empty($x));

$x = NULL;
var_dump(empty($x));

$x = "";
var_dump(empty($x));

$x = '';
var_dump(empty($x));

$x = "0";
var_dump(empty($x));

$x = 0;
var_dump(empty($x));

$x = false;
var_dump(empty($x));

$x = array();
var_dump(empty($x));

?>
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)
bool(true)

Now when you are validating forms to make sure a user did not leave a form field blank, it is probably best to use neither empty() or isset() (not that isset would work). Since it is possible your form might accept 0 as a valid answer. Therefore you should just check to make sure it is not an empty string.

1
2
3
4
5
<?php
if($_GET['foo'] == "") {
    echo "You must enter a value for foo!";
}
?>

Tags: ,


2 Responses to “isset vs. empty”

  1. social_experiment Says:

    Good post, i recently [also] discovered that testing with a 0 will return true if empty() is used. The implications are obvious and since then i always check if the string is empty ( $variable == ” ) instead of using if ( empty($variable) )

    Reply