wp_validate_boolean()WP 4.0.0

Turns the value of the specified variable into a logical true or false.

Alternative to the construct: filter_var( $var, FILTER_VALIDATE_BOOLEAN ).

No Hooks.

Return

true|false. Whether the value is validated.

Usage

wp_validate_boolean( $var );
$var(mixed) (required)
Boolean value to validate.

Examples

0

#1 Demonstration of work

$var = wp_validate_boolean( true );           // bool(true)
$var = wp_validate_boolean( 'true' );         // bool(true)
$var = wp_validate_boolean( '11' );           // bool(true)
$var = wp_validate_boolean( 1 );              // bool(true)
$var = wp_validate_boolean( 'on' );           // bool(true)
$var = wp_validate_boolean( 'off' );          // bool(true)
$var = wp_validate_boolean( 'foo' );          // bool(true)
$var = wp_validate_boolean( new StdClass() ); // bool(true)
$var = wp_validate_boolean( [1] );            // bool(true)

$var = wp_validate_boolean( 'false' ); // bool(false)
$var = wp_validate_boolean( false );   // bool(false)
$var = wp_validate_boolean( 0 );       // bool(false)
$var = wp_validate_boolean( '0' );     // bool(false)
$var = wp_validate_boolean( '' );      // bool(false)
$var = wp_validate_boolean( null );    // bool(false)
$var = wp_validate_boolean( [] );      // bool(false)
0

#2 Let's make sure we transmit logical data

Sometimes you need to know exactly what logical data is passed, for example when we work with JSON. PHP understands '0' as false, but JSON understands it differently, and in these cases we have to make sure that it's the logical data being passed. Let's say we pass settings:

$json_data = array(
	'tracklist'    => wp_validate_boolean( $atts['tracklist'] ),
	'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
	'images'       => wp_validate_boolean( $atts['images'] ),
	'artists'      => wp_validate_boolean( $atts['artists'] ),
);

echo json_encode( $json_data );
0

#3 Ensure the value is bool

// example 1
$status = isset( $plugin_data['status'] ) ? wp_validate_boolean( $plugin_data['status'] ) : false;
$plugin_status = isset( $plugin_data['active'] ) ? wp_validate_boolean( $plugin_data['active'] ) : false;

// example 2
$is = true === wp_validate_boolean( $request->get_param( 'fetch_field_data' ) )

Changelog

Since 4.0.0 Introduced.

Code of wp_validate_boolean() WP 5.9.3

function wp_validate_boolean( $var ) {
	if ( is_bool( $var ) ) {
		return $var;
	}

	if ( is_string( $var ) && 'false' === strtolower( $var ) ) {
		return false;
	}

	return (bool) $var;
}