rest_is_boolean()WP 4.7.0

Determines if a given value is a boolean or boolean-like. Doesn't look at the type of a given value, and like in PHP, 1 = true and 0 = false.

1 time — 0.000001 sec (speed of light) | 50000 times — 0.02 sec (speed of light) | PHP 7.1.11, WP 4.9.8

No Hooks.

Return

true|false. True if a boolean, otherwise false.

Usage

rest_is_boolean( $maybe_bool );
$maybe_bool(true|false|string) (required)
The value being evaluated.

Examples

0

#1 Check if the following values are boolean or boolean-like

var_dump( rest_is_boolean( true ) );        // true
var_dump( rest_is_boolean( false ) );       // true
var_dump( rest_is_boolean( 'false' ) );     // true
var_dump( rest_is_boolean( 'true' ) );      // true
var_dump( rest_is_boolean( 'FalSe' ) );     // true
var_dump( rest_is_boolean( 'trUe' ) );      // true
var_dump( rest_is_boolean( 1 ) );           // true
var_dump( rest_is_boolean( 0 ) );           // true
var_dump( rest_is_boolean( '1' ) );         // true
var_dump( rest_is_boolean( '0' ) );         // true

// The the next return false
var_dump( rest_is_boolean( 'trueFalse' ) ); // false
var_dump( rest_is_boolean( 'anyString' ) ); // false
var_dump( rest_is_boolean( 1.0 ) );         // false
var_dump( rest_is_boolean( 2 ) );           // false
var_dump( rest_is_boolean( -1 ) );          // false
var_dump( rest_is_boolean( -2 ) );          // false
var_dump( rest_is_boolean( '-1' ) );        // false
var_dump( rest_is_boolean( '2' ) );         // false

Changelog

Since 4.7.0 Introduced.

rest_is_boolean() code WP 6.6.2

function rest_is_boolean( $maybe_bool ) {
	if ( is_bool( $maybe_bool ) ) {
		return true;
	}

	if ( is_string( $maybe_bool ) ) {
		$maybe_bool = strtolower( $maybe_bool );

		$valid_boolean_values = array(
			'false',
			'true',
			'0',
			'1',
		);

		return in_array( $maybe_bool, $valid_boolean_values, true );
	}

	if ( is_int( $maybe_bool ) ) {
		return in_array( $maybe_bool, array( 0, 1 ), true );
	}

	return false;
}