How to Evaluate String 'false' in PHP?

Find out ways to evaluate a string 'false' as boolean false in PHP

In PHP, "false" (i.e. string false) is not type converted to boolean false automatically. In fact, it evaluates to true which is actually the correct interpretation because in PHP, any value other than falsy values will always return true when evaluated. Since "false" is a non-empty string, it is by definition truthy. However, in some cases, such as when making an HTTP request to the server, this might not be the result you expect. Therefore, to interpret string "false" as boolean false, you can do any of the following:

Using json_decode()

As long as you have a valid JSON string, you can simply use the json_decode() function. It would correctly convert any string boolean value to boolean type. For example:

json_decode('false') // bool(false)

Please note that this function only works with UTF-8 encoded strings.

Using filter_var()

You can use the filter_var() function with the FILTER_VALIDATE_BOOL filter (or FILTER_VALIDATE_BOOLEAN for PHP versions below 8). This returns true only for "1", "true", "on" and "yes", everything else returns false. For example:

filter_var('', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('0.0', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('0', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('null', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('false', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('array()', FILTER_VALIDATE_BOOL) // bool(false)
filter_var('[]', FILTER_VALIDATE_BOOL) // bool(false)

filter_var('true', FILTER_VALIDATE_BOOL) // bool(true)
filter_var(1, FILTER_VALIDATE_BOOL) // bool(true)
filter_var('1', FILTER_VALIDATE_BOOL) // bool(true)
filter_var('on', FILTER_VALIDATE_BOOL) // bool(true)
filter_var('yes', FILTER_VALIDATE_BOOL) // bool(true)

If you use the FILTER_VALIDATE_BOOL filter and specify FILTER_NULL_ON_FAILURE as the option, then false is only returned for "0", "false", "off", "no", and "", and null is returned for all non-boolean values. For example:

filter_var('foo', FILTER_VALIDATE_BOOL) // false
filter_var('foo', FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) // null

filter_var('0.0', FILTER_VALIDATE_BOOL) // false
filter_var('0.0', FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) // null

filter_var('[]', FILTER_VALIDATE_BOOL) // false
filter_var('[]', FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) // null

filter_var('null', FILTER_VALIDATE_BOOL) // false
filter_var('null', FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) // null

Using "1" For Truthy and "0" For Falsy Values

You could simply consider sending boolean values to PHP as their integer counterparts '1' and '0' (as 1, of string or integer type, is considered a truthy value and 0, of string or integer type, is considered a falsy value):

if ('1') // true
if ('0') // false

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.