Checks whether a value is unset or false-like without raising an undefined-variable notice.
What Is empty() in PHP?
Checks whether a value is unset or false-like without raising an undefined-variable notice.
Its syntax is:
empty(mixed $var): bool
Parameters:
$var— Accepted as mixed; required argument.
Return type: bool. The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
Availability: empty is a language construct, not a normal callable function.
Example 1: Basic Usage
<?php
$items = []; var_dump(empty($items));
Output:
bool(true)
The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
Example 2: A Different Input
<?php
$flag = "0"; var_dump(empty($flag));
Output:
bool(true)
The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
Practical Example: Applying It in a Program
<?php
$request = ["page" => "0", "search" => "report"]; echo empty($request["page"]) ? "No page selected" : "Page present";
Output:
No page selected
The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
Important Behavior and Edge Cases
- Key behavior: The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
- Environment: empty is a language construct, not a normal callable function.
Comparison With Related Functions
| Function | Purpose |
|---|---|
empty() | Checks whether a value is unset or false-like without raising an undefined-variable notice. |
isset() and array_key_exists() | isset() tests defined, non-null values; array_key_exists() tests key presence even for null. empty() instead tests PHP falsiness. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: The string "0", integer zero, false, null and an empty array all count as empty | The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness. |
Key Takeaways
- Checks whether a value is unset or false-like without raising an undefined-variable notice.
- The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.
- empty is a language construct, not a normal callable function.
Summary: The string "0", integer zero, false, null and an empty array all count as empty. Use array_key_exists() or isset() when presence matters more than truthiness.