How to string to boolean in PHP

Sometimes, when working with JSON data in PHP, you may encounter a situation where you need to cast a string value to a boolean value. For example, you may have a JSON field that stores a boolean value as a string, such as “true” or “false”.

To convert a string to a boolean value in PHP, you can use the filter_var() function with the FILTER_VALIDATE_BOOLEAN flag. The filter_var() function takes two arguments: the first argument is the string to be converted, and the second argument is the filter to apply.

The FILTER_VALIDATE_BOOLEAN filter is used to validate a boolean value. If the string can be converted to a boolean value, the function returns true or false. If the string cannot be converted, the function returns false.

In the given code snippet, the filter_var() function is used to convert different string values to boolean values using the FILTER_VALIDATE_BOOLEAN flag. If the string can be converted to a boolean value, the function returns true, and if it cannot be converted, the function returns false.

BONUS TIP: If you are using the Laravel framework, you can use the boolean() method of the Illuminate\Http\Request class to convert a string value to a boolean value. For example, the $request->boolean('active') code snippet converts the value of the active parameter in the HTTP request to a boolean value.


// Plain PHP
filter_var('true', FILTER_VALIDATE_BOOLEAN); // true
filter_var('1', FILTER_VALIDATE_BOOLEAN); // true
filter_var('on', FILTER_VALIDATE_BOOLEAN); // true
filter_var('yes', FILTER_VALIDATE_BOOLEAN); // true

filter_var('false', FILTER_VALIDATE_BOOLEAN); // false
filter_var('0', FILTER_VALIDATE_BOOLEAN); // false
filter_var('off', FILTER_VALIDATE_BOOLEAN); // false
filter_var('no', FILTER_VALIDATE_BOOLEAN); // false
filter_var('', FILTER_VALIDATE_BOOLEAN); // false


// Using Laravel 
use Illuminate\Http\Request;
...
$request->boolean('active')