Converts a value to a boolean using PHP truthiness rules.
What Is boolval() in PHP?
Converts a value to a boolean using PHP truthiness rules.
Its syntax is:
boolval(mixed $value): bool
Parameters:
$value— Accepted as mixed; required argument.
Return type: bool. Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
Availability: Available in standard PHP.
Example 1: Basic Usage
<?php
var_dump(boolval(0));
Output:
bool(false)
Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
Example 2: A Different Input
<?php
var_dump(boolval("false"));
Output:
bool(true)
Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
Practical Example: Applying It in a Program
<?php
$inputs = [0, 1, "", "yes", "0"];
foreach ($inputs as $input) { var_export(boolval($input)); echo PHP_EOL; }
Output:
false
true
false
true
false
Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
Important Behavior and Edge Cases
- Key behavior: Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
- Environment: Available in standard PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
boolval() | converts a value to a boolean using PHP truthiness rules. |
filter_var() | filter_var() can apply an explicit validation or boolean filter; boolval() simply applies PHP truthiness rules. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: Non-empty strings such as "false" are true; only the empty string and string "0" are false | Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation. |
Key Takeaways
- converts a value to a boolean using PHP truthiness rules.
- Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.
- Available in standard PHP.
Summary: Non-empty strings such as "false" are true; only the empty string and string "0" are false. For web form booleans use explicit validation.