Booleans
This is the simplest type. A bool expresses a truth value. It can be either true or false .
Syntax
To specify a bool literal, use the constants true or false . Both are case-insensitive.
$foo = True; // assign the value TRUE to $foo ?>
Typically, the result of an operator which returns a bool value is passed on to a control structure.
// == is an operator which tests // equality and returns a boolean if ($action == "show_version") < echo "The version is 1.23"; > // this is not necessary. if ($show_separators == TRUE) < echo "
\n"; > // . because this can be used with exactly the same meaning: if ($show_separators) < echo "
\n"; > ?>
Converting to boolean
To explicitly convert a value to bool, use the (bool) or (boolean) casts. However, in most cases the cast is unnecessary, since a value will be automatically converted if an operator, function or control structure requires a bool argument.
When converting to bool, the following values are considered false :
- the booleanfalse itself
- the integer 0 (zero)
- the floats 0.0 and -0.0 (zero)
- the empty string, and the string «0»
- an array with zero elements
- the special type NULL (including unset variables)
- SimpleXML objects created from attributeless empty elements, i.e. elements which have neither children nor attributes.
Every other value is considered true (including any resource and NAN ).
-1 is considered true , like any other non-zero (whether negative or positive) number!
var_dump((bool) ""); // bool(false) var_dump((bool) "0"); // bool(false) var_dump((bool) 1); // bool(true) var_dump((bool) -2); // bool(true) var_dump((bool) "foo"); // bool(true) var_dump((bool) 2.3e5); // bool(true) var_dump((bool) array(12)); // bool(true) var_dump((bool) array()); // bool(false) var_dump((bool) "false"); // bool(true) ?>
PHP 8.2
For any of the types int, float, string, bool and resource, converting value to array results with single element index zero scalar which was converted.
Type declarations can be added to function arguments, return values, and, as PHP 7.4.0, class properties.
Булев
Это простейший тип. boolean выражает истинность значения. Он может быть либо TRUE , либо FALSE .
Синтаксис
Для указания boolean , используйте константы TRUE или FALSE . Обе они регистронезависимы.
Обычно, некоторый оператор возвращает boolean значение, которое потом передается управляющей конструкции.
// == это оператор, который проверяет
// эквивалентность и возвращает boolean
if ( $action == «show_version» ) echo «The version is 1.23» ;
>
?php
// это необязательно.
if ( $show_separators == TRUE ) echo «
\n» ;
>
// . потому что следующее имеет тот же самый смысл:
if ( $show_separators ) echo «
\n» ;
>
?>
Преобразование в булев тип
Для явного преобразования в boolean , используйте (bool) или (boolean). Однако, в большинстве случаев приведение типа необязательно, так как значение будет автоматически преобразовано, если оператор, функция или управляющая конструкция требует boolean аргумент.
При преобразовании в boolean , следующие значения рассматриваются как FALSE :
- само значение booleanFALSE
- integer 0 (ноль)
- float 0.0 (ноль)
- пустая строка, и строка «0»
- массив без элементов
- объект без полей (только для PHP 4)
- особый тип NULL (включая неустановленные переменные)
- Объекты SimpleXML, созданные из пустых тегов
Все остальные значения рассматриваются как TRUE (включая любой resource).
-1 рассматривается как TRUE , как и любое другое ненулевое (отрицательное или положительное) число!
var_dump ((bool) «» ); // bool(false)
var_dump ((bool) 1 ); // bool(true)
var_dump ((bool) — 2 ); // bool(true)
var_dump ((bool) «foo» ); // bool(true)
var_dump ((bool) 2.3e5 ); // bool(true)
var_dump ((bool) array( 12 )); // bool(true)
var_dump ((bool) array()); // bool(false)
var_dump ((bool) «false» ); // bool(true)
?>?php
PHP Boolean
A boolean value represents a truth value. In other words, a boolean value can be either true or false . PHP uses the bool type to represent boolean values.
To represent boolean literals, you can use the true and false keywords. These keywords are case-insensitive. Therefore, the following are the same as true :
And the following are the same as false :
When you use non-boolean values in a boolean context, e.g., if statement. PHP evaluates that value to a boolean value. The following values evaluate to false :
- The keyword false
- The integer zero (0)
- The floating-point number zero (0.0)
- The empty string ( » ) and the string «0»
- The NULL value
- An empty array, i.e., an array with zero elements
PHP evaluates other values to true .
The following shows how to declare variables that hold Boolean values:
$is_submitted = false; $is_valid = true;
Code language: PHP (php)
To check if a value is a Boolean, you can use the built-in function is_bool() . For example:
$is_email_valid = false; echo is_bool($is_email_valid);
Code language: PHP (php)
When you use the echo to show a boolean value, it’ll show 1 for true and nothing for false , which is not intuitive. To make it more obvious, you can use the var_dump() function. For example:
$is_email_valid = false; var_dump($is_email_valid); $is_submitted = true; var_dump($is_submitted);
Code language: HTML, XML (xml)
bool(false) bool(true)
Code language: JavaScript (javascript)
Summary
- A boolean value represents a truth value, which is either true or false .
- PHP evaluates the following values to false: false, 0, 0.0, empty string (“”), “0”, NULL, an empty array; other values are true .
PHP Booleans
Before understanding what is PHP Boolean, let’s understand what is Boolean?
Web development, programming languages, Software testing & others
Boolean is a data type that is used in most computer programming languages like Java, Python, C, PHP, etc. It is a data type that has one or two possible values (either true or false). It is intended to represent the two truth values of logic and Boolean algebra. Depending upon the conditions it will set its value as 1(true) or 0(false). This data type is used by many programming languages to check if the condition satisfies and the statements get executed.
In PHP, the boolean data type is used to set the values of the variables. It is mostly used for conditional statements like If, While, For, Switch, Etc. These conditional and iterative commands are mostly defined to test these boolean-valued expressions. Boolean value returns only two values i.e. either true or false. so, it is used in conditional statements to pass through that particular condition to execute the following statements corresponding to it.
Types of PHP Booleans Value
Let’s take a look at different types of boolean values:
- Integer: This Boolean value is used to check the condition of whether the variable’s output is non-zero. If the output is zero, then the condition is false and the statements will not be executed presently inside the loop and will skip the loop and execute the further statements.
- Floating Point: This Boolean value is used to check the condition of whether the variable’s output is a floating number for e.g. 0.0. If the output is non-zero, then the condition is true and the loop statements will be executed, if the output is zero then the statements inside the loop will be skipped and will proceed to execute the further statements.
- Strings: This Boolean value is used to check whether the string is empty or not. If the output of the conditional statement is true, then the output will be a string value and the statements inside the loop will get executed. If the output is false, then the output is either a zero string or an empty string.
- Array: This Boolean value is used to check whether an array has elements in it. If the condition is true, then it must be having at least one number of element and the statements inside the loop will get executed. If the condition is false, then the output must be an empty array and will skip the statements inside the loop and will proceed to execute the further statements.
- NULL: This Boolean value is used to check whether the variable’s value is NULL. A variable’s value will be NULL if it is initialized to NULL at the beginning itself or it has not been set any value or it is unset. If the condition is true, then statements inside the loop will get executed. If the output is false, it will skip the statements inside the loop and will proceed to execute the further statements.
- Objects: This Boolean value is used to check whether an object is present or not. If it is present, then the condition is true and the statements will be executed and the condition is false, then it will skip the statements inside the loop and will proceed to execute the further statements.
How Boolean Value Works?
Boolean values are nothing but 0 and 1 i.e. either true or false. if the condition satisfies, it is true else it is false.
Example #1
Let’s consider simple examples to understand how Boolean value works.
In the above example, the output is a non-zero. Therefore, the statements inside if the statement is not executed.
Example #2
Let’s take another example for string Boolean value:
In the above example, the name is non-empty and also no comparison operator is used. PHP automatically converts the value and sets it to its Boolean equivalent true. So the statements will be executed written inside if statement.
Example #3
Let’s take another example:
In the above example, the $var variable has been initialized to null. So the condition becomes true and the statement written inside the loop gets executed and sets the value to 500.
Example #4
The function is_bool () can be used to check whether a variable contains a Boolean value or not. The is_bool () is an inbuilt function in PHP. It is a Boolean function so it returns TRUE when the value is a Boolean value, otherwise FALSE. Let’s take a simple example.
'; echo $b.'
'; echo is_bool($a).'
'; echo is_bool ($b).'
'; ?>
In the above example, the output of the function is_bool() will be either 0 or 1. In this example, the output will be 1 and after the break also it will be 1. It just checks whether the Boolean value is set to the variable and in this example, both the variables have been initialized Boolean values.
Example #5
Similar to is_bool () function, we have a function called var_dump () function to print both the type as well as the value as output. This function is used to print the data type associated with the variable that the developers want to print on the screen.
In the above example, the output of is_bool() function and var_dump function() differs. The var_dump() function will print the data type along with the value of the variable.
Conclusion
In this article, we discussed the Boolean value and its types. Many of the Boolean types are used in many programs and applications. Boolean values play a vital role in many programming languages especially in PHP where we use cookies and sessions to check whether they are set or unset.
Recommended Articles
This is a guide to PHP Booleans. Here we discuss the basic concept with different types of PHP booleans, it’s working along with examples and code implementation. You may also look at the following articles to learn more –
500+ Hours of HD Videos
15 Learning Paths
120+ Courses
Verifiable Certificate of Completion
Lifetime Access
1000+ Hours of HD Videos
43 Learning Paths
250+ Courses
Verifiable Certificate of Completion
Lifetime Access
1500+ Hour of HD Videos
80 Learning Paths
360+ Courses
Verifiable Certificate of Completion
Lifetime Access
3000+ Hours of HD Videos
149 Learning Paths
600+ Courses
Verifiable Certificate of Completion
Lifetime Access
All in One Software Development Bundle 3000+ Hours of HD Videos | 149 Learning Paths | 600+ Courses | Verifiable Certificate of Completion | Lifetime Access
Financial Analyst Masters Training Program 1000+ Hours of HD Videos | 43 Learning Paths | 250+ Courses | Verifiable Certificate of Completion | Lifetime Access