The bool_from_yn() WordPress PHP function determines whether the input is ‘yes’ or ‘no’. It returns ‘true’ if the input is ‘y’, and ‘false’ otherwise.
Usage
This is a basic way to use the function:
$answer = bool_from_yn('y');
In this case, $answer will be true because the input is ‘y’.
Parameters
$yn(string) – This is a required parameter. It’s a character string containing either ‘y’ (for yes) or ‘n’ (for no).
More information
See WordPress Developer Resources: bool_from_yn()
Examples
Basic Usage
In this example, we determine if the string ‘y’ is a ‘yes’.
$answer = bool_from_yn('y');
echo $answer; // Will output: 1
Evaluating ‘No’
Here, we evaluate ‘n’ as ‘no’, which will return false.
$answer = bool_from_yn('n');
echo $answer; // Will output nothing as 'false' is interpreted as empty
Input from a Form
Let’s assume we have a form where users can input ‘y’ or ‘n’. We can use our function to evaluate the user’s input.
$user_input = $_POST['user_input']; $is_yes = bool_from_yn($user_input);
Use in Conditional Statements
We can use this function in a conditional statement to trigger different actions for ‘yes’ and ‘no’.
$answer = 'y';
if(bool_from_yn($answer)) {
echo "You answered yes!";
} else {
echo "You answered no!";
}
Validating Data
Lastly, we can use this function to validate data. If the input is not ‘y’, we assume it’s ‘no’.
$data = 'x';
$is_yes = bool_from_yn($data);
if($is_yes) {
echo "Data is valid!";
} else {
echo "Data is not valid!";
}