To check if a variable is boolean is one thing, to evaluate if the value of a variable represents a boolean condition (true or false) is another.
Here is a simple function that checks the status of the received variable in regard to boolean equivalencies (case-insensitive).
<?php
/**
* Check "Booleanic" Conditions :)
*
* @param [mixed] $variable Can be anything (string, bol, integer, etc.)
* @return [boolean] Returns TRUE for "1", "true", "on" and "yes"
* Returns FALSE for "0", "false", "off" and "no"
* Returns NULL otherwise.
*/
function is_enabled($variable)
{
if (!isset($variable)) return null;
return filter_var($variable, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
}
?>
Of course, it is a simplistic approach, but for the majority of cases it will do the job right.
And, just to put the thing from the right perspective, here's a real function that does what Phill disclosed:
<?php
/**
* Convert $variable to boolean (adapted from Phill answer)
*
* @param [mixed] $variable Can be anything
* @return [boolean] Returns the booelan equivalent to $variable based on Zend Enegine interpretation
*/
function to_bool($variable)
{
return (bool)$variable;
}
?>
I hope it helps someone. Happy coding.
PHP.mk документација
is_bool
Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.
Патека
function.is-bool.php
Локална патека за оваа страница.
Извор
php.net/manual/en
Оригиналниот HTML се реупотребува и локално се стилизира.
Режим
Прокси + превод во позадина
Кодовите, табелите и белешките остануваат читливи во истиот тек.
Референца
function.is-bool.php
is_bool
Референца за `function.is-bool.php` со подобрена типографија и навигација.
is_bool
(PHP 4, PHP 5, PHP 7, PHP 8)
is_bool — Открива дали променливата е булова
Параметри
value-
Променливата што се оценува.
Вратени вредности
Патеката до PHP скриптата што треба да се провери. true if value е bool,
false otherwise.
Примери
Пример #1 is_bool() examples
<?php
$a = false;
$b = 0;
// Since $a is a boolean, it will return true
if (is_bool($a) === true) {
echo "Yes, this is a boolean\n";
}
// Since $b is not a boolean, it will return false
if (is_bool($b) === false) {
echo "No, this is not a boolean\n";
}
?>Види Исто така
- is_float() - Дознајте дали типот на променливата е float
- is_int() - Дознајте дали променливата е цел број
- is_string() - Finds whether a variable is a scalar
- is_object() - Дознајте дали променливата е објект
- is_array() - Пронајдете дали променлива е низа
Белешки од корисници 2 забелешки
Јулио Марки ¶
пред 6 години
phil ¶
пред 7 години
It should be stated that this function returns true if the _type_ of it's argument is boolean. It does not convert or coerce the value to a boolean type, not sure why so many comments focus on how to do this.
However, if you arrived here looking for a solution to convert a value to a boolean type, use this:
to_bool($x) { return (bool)$x; }