Three small functions help you check what a variable holds and remove it. You will use them constantly, especially with form data.
isset(): does it exist and is it not null?
<?php
$name = "Rhea";
$nothing = null;
var_dump(isset($name));
var_dump(isset($nothing));
var_dump(isset($missing));
bool(true)
bool(false)
bool(false)
isset() is true only when the variable exists and is not null. It never gives a warning, even for a variable that does not exist, so it is the safe way to test.
You can pass several variables. The answer is true only if all of them are set.
<?php
$a = 1;
$b = 2;
var_dump(isset($a, $b));
var_dump(isset($a, $c));
bool(true)
bool(false)
empty(): is it “empty”?
empty() is true for a variable that is missing or holds a value that PHP treats as empty:
""(an empty string)0and0.0"0"(the string zero)nullandfalse[](an empty array)
<?php
var_dump(empty(""));
var_dump(empty("0"));
var_dump(empty(0));
var_dump(empty("hello"));
var_dump(empty([]));
bool(true)
bool(true)
bool(true)
bool(false)
bool(true)
The "0" trap
0 in a form (a quantity or an age). empty("0") is true, so you would reject a valid value. For form fields, compare with "" instead. Handling Empty Values goes deeper.unset(): remove a variable
<?php
$token = "abc123";
unset($token);
var_dump(isset($token));
bool(false)
unset() also removes an item from an array.
<?php
$user = ["name" => "Rhea", "password" => "secret"];
unset($user["password"]);
print_r($user);
Array
(
[name] => Rhea
)
Quick rule
isset() to ask “is there a value?” and empty() to ask “is there a useful value?”. When 0 or “0” is a valid input, use isset() and a strict comparison instead of empty().