Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value.
Examples:
Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN);
Output : true
Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN);
Output : false
Approach using PHP filter_var() Function: The filter_var() function is used to filter a variable with specified filter. This function is used to both validate and sanitize the data.
Syntax:
filter_var( var, filterName, options )
Parameters: This function accepts three parameters as mentioned above and described below:
- var: It is the required field. It denotes the variable to filter.
- filterName: It is used to specify the ID or name of the filter to use. The default filter is FILTER_DEFAULT. It is optional field.
- options: It is used to specify one or more flags/options to use. Check each filter for possible options and flags. It is also optional field.
Return Value: Returns the filtered data on success, or False on failure.
Program:
<?php
var_dump(filter_var( 'true' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( '1' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( 'on' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( 'yes' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( 'false' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( '0' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( 'off' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( 'no' , FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var( '' , FILTER_VALIDATE_BOOLEAN));
?>
|
Output:
bool(true)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
bool(false)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!