Course Content
About Lesson

isset() and empty()

These two functions are important when working with forms, variables, and conditions.

isset() checks if a variable is set and not NULL.

PHP
<?php
$name = "John";

if (isset($name)) {
    echo "The variable 'name' is set.";
} else {
    echo "The variable 'name' is not set.";
}
?>

Output: The variable ‘name’ is set.

If we don’t declare $name, then isset($name) will return false.

empty() checks if a variable is empty. A variable is considered empty if it is:

  • "" (empty string)
  • 0 (integer zero)
  • 0.0 (float zero)
  • "0" (string zero)
  • NULL
  • false
  • An empty array []
PHP
<?php
$age = 0;

if (empty($age)) {
    echo "The variable 'age' is empty.";
} else {
    echo "The variable 'age' has a value.";
}
?>

Output: The variable ‘age’ is empty.

If we don’t declare $name, then isset($name) will return false.

FunctionReturns TRUE when…
isset()Variable exists and is NOT NULL
empty()Variable is empty ( “”, 0, “0”, NULL, false, [] )
PHP
<!DOCTYPE html>
<html>
<head>
    <title>isset() and empty() Example</title>
</head>
<body>

<form method="post" action="">
    Name: <input type="text" name="name">
    <input type="submit" name="submit" value="Submit">
</form>

<?php
if (isset($_POST['submit'])) {  // Check if form is submitted
    $name = $_POST['name'];

    if (empty($name)) {
        echo "<p style='color:red;'>Name cannot be empty!</p>";
    } else {
        echo "<p style='color:green;'>Hello, " . $name . "!</p>";
    }
}
?>
</body>
</html>

Explanation:

  • isset($_POST['submit']) → checks if the Submit button was clicked.
  • empty($name) → checks if the input box is empty.