Boolean variables in php general information. Default selection

Last update: 1.11.2015

In PHP we can use various operators: arithmetic, logical, etc. Let's look at each type of operation.

Arithmetic operations

    + (addition operation)

    For example, $a + 5

    - (subtraction operation)

    For example, $a - 5

    * (multiplication)

    For example, $a * 5

    / (division)

    For example, $a / 5

    % (obtaining the remainder of division)

    For example: $a=12; echo $a % 5; // equals 2

    ++ (increment/increase value by one)

    For example, ++$a

    It is important to understand the difference between the expressions ++$a and $a++ . For example:

    $a=12; $b=++$a; // $b is equal to 13 echo $b;

    Here, first, one is added to the value of the variable $a, and then its value is equated to the variable $b. It would be different if the expression looked like this: $b=$a++; . Here, first the value of the variable $a was equal to the variable $b, and then the value of the variable $a was increased.

    -- (decrement/decrease value by one)

    For example, --$a . And also, as in the case of increment, there are two types of recording: --$a and $a--

Assignment Operators

    Equates a variable to a specific value: $a = 5

    Addition followed by assignment of the result. For example: $a=12; $a += 5; echo $a; // equal to 17

    Subtraction followed by assignment of the result. For example: $a=12; $a -= 5; echo $a; // equals 7

    Multiplication followed by assignment of the result: $a=12; $a *= 5; echo $a; // equals 60

    Division followed by assignment of the result: $a=12; $a /= 5; echo $a; // equal to 2.4

    Concatenate rows and assign the result. Applies to two lines. If the variables do not store strings, but, for example, numbers, then their values ​​are converted to strings and then the operation is performed: $a=12; $a .= 5; echo $a; // equal to 125 // identical to $b="12"; $b .="5"; // equal to 125

    Obtaining the remainder of division and then assigning the result: $a=12; $a %= 5; echo $a; // equals 2

Comparison Operations

Comparison operations are usually used in conditional structures when it is necessary to compare two values ​​and, depending on the result of the comparison, perform certain actions. Available following operations comparisons.

    The equality operator compares two values, and if they are equal, returns true, otherwise returns false: $a == 5

    The identity operator also compares two values, and if they are equal, returns true, otherwise returns false: $a === 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $a != 5

    Compares two values, and if they are not equal, returns true, otherwise returns false: $a !== 5

    Compares two values, and if the first is greater than the second, then returns true, otherwise returns false: $a > 5

    Compares two values, and if the first is less than the second, then returns true, otherwise returns false: $a< 5

    Compares two values, and if the first is greater than or equal to the second, then returns true, otherwise returns false: $a >= 5

    Compares two values, and if the first is less than or equal to the second, then returns true, otherwise returns false: $a<= 5

Equality and identity operator

Both operators compare two expressions and return true if the expressions are equal. But there are differences between them. If the equality operation takes two values ​​of different types, then they are reduced to one - the one that the interpreter finds optimal. For example:

Obviously, variables store different values ​​of different types. But when compared, they will be reduced to the same type - numeric. And the variable $a will be reduced to the number 22. And in the end, both variables will be equal.

Or, for example, the following variables will also be equal:

$a = false; $b = 0;

To avoid such situations, the equivalence operation is used, which takes into account not only the value, but also the type of the variable:

$a = "22a"; $b = 22; if($a===$b) echo "equal"; else echo "not equal";

Now the variables will not be equal.

The inequality operators != and !== work similarly.

Logical operations

Logical operations are typically used to combine the results of two comparison operations. For example, we need to perform a certain action if several conditions are true. The following logical operations are available:

    Returns true if both comparison operations return true, otherwise returns false: $a == 5 && $b = 6

    Similar to the && operation: $a == 5 and $b > 6

    Returns true if at least one comparison operation returns true, otherwise returns false: $a == 5 || $b = 6

    Similar to the operation || : $a< 5 or $b > 6

    Returns true if the comparison operation returns false: !($a >= 5)

    Returns true if only one of the values ​​is true. If both are true or neither is true, returns false. For example: $a=12; $b=6; if($a xor $b) echo "true"; else echo "false";

    Here the result of the logical operation will be false since both variables have a specific value. Let's change the code:

    $a=12; $b=NULL; if($a xor $b) echo "true"; else echo "false";

    Here the result will already be true, since the value of one variable is not set. If a variable has the value NULL, then in logical operations its value will be treated as false

Bit operations

Bit operations are performed on individual bits of a number. Numbers are considered in binary representation, for example, 2 in binary representation is 010, the number 7 is 111.

    & (logical multiplication)

    Multiplication is performed bitwise, and if both operands have bit values ​​equal to 1, then the operation returns 1, otherwise the number 0 is returned. For example: $a1 = 4; //100 $b1 = 5; //101 echo $a1 & $b1; // equals 4

    Here the number 4 in the binary system is 100, and the number 5 is 101. Multiply the numbers bit by bit and get (1*1, 0*0, 0 *1) = 100, that is, the number 4 in decimal format.

    | (logical addition)

    Similar to logical multiplication, the operation is also performed on binary digits, but now one is returned if at least one number in a given digit has a one. For example: $a1 = 4; //100 $b1 = 5; //101 echo $a1 | $b1; // equals 5

    ~ (logical negation)

    inverts all bits: if the bit value is 1, then it becomes zero, and vice versa. $b = 5; echo ~$b;

    x<

    x>>y - shifts the number x to the right by y digits. For example, 16>>1 shifts 16 (which is 10000 in binary) one place to the right, resulting in 1000 or 8 in decimal

Concatenating Strings

The dot operator is used to concatenate strings. For example, let's connect several lines:

$a="Hello,"; $b=" world"; echo $a . $b . "!";

If the variables represent other types than strings, such as numbers, then their values ​​are converted to strings and then the string concatenation operation also occurs.

PHP supports the standard logical operators AND and && , OR and || , ! (not) and XOR . Logical operators allow you to compare the results of two operands (a value or an expression) to determine whether one or both return true or false and choose whether to continue executing the script accordingly based on the returned value. Like comparison operators, logical operators return a single Boolean value - true or false, depending on the values ​​on either side of the operator.

Logical OR (OR and ||)

The logical OR operator is denoted as OR or || . It performs a logical OR operation on two operands. If one or both operands are true, it returns true. If both operands are false, it returns false. You probably have a question: why did they make two versions of one operator? The meaning of two different options The logical OR operator is that they operate with different priorities.

First, let's look at how the || operator works. . And so, if one or both of its operands are true, it returns true . If both operands return false values, it will return false .

The OR operator works the same as the || operator. with one exception, if the OR operator is used with an assignment, it will first evaluate and return the value of the left operand, otherwise it works exactly the same as the || operator. , i.e. if one or both of its operands are true, it returns true . If both operands return false, it will return false .

To make it clearer how they work, let's give the following example:

1 // First the variable is assigned the value false, and then the second operand is evaluated // Priority action: ($var2 = false) or true $var2 = false or true; echo $var2; // false is not printed // ($var3 = 0) or 3 $var3 = 0 or 3; echo "
$var3"; // => 0 ?>

Any comparison and logical operators can be combined into more complex structures:

One more thing worth mentioning important point, regarding both the OR and || . The logical OR operator begins its calculations with its left operand; if it returns true, then the right operand will not be evaluated. This saves execution time, but you must be careful to ensure that code that may depend on correct work program was not placed in the right operand.

Logical AND (AND and &&)

The logical AND operator is denoted as AND or && . It performs a logical AND operation on two operands. It returns true if and only if both operands evaluate to true . If one or both operands return false , the operator returns false . The meaning of the two different versions of the “logical AND” operator is the same as the two previous operators, namely, that they work with different priorities.

First, let's look at how the && operator works. And so, if both of its operands are true, it returns true . If at least one or both of its operands return false , it will also return false .

The AND operator works the same as the && operator with one exception, if the AND operator is used with an assignment, it will first evaluate and return the value of the left operand, otherwise it works exactly the same as the && operator. If at least one of its operands returns false, it will also return false, and if both operands return false, it will return false.

To understand, let’s now look at how this works in practice:

$bar3"; // => 9 ?>

Exclusive OR (XOR)

The exclusive OR operator is denoted as XOR. It returns true if one and only one of its operands is true. If both operands are true, the operator will return false.

Because the XOR operator has the same precedence as the AND and OR operators (lower than the assignment operator), and it is used in an assignment expression, it first evaluates and returns the value of the left operand.

6 $a1 = 19 xor 5 > 6; var_dump($a1); // => 19 var_dump(true xor true); // false var_dump((2< 3) xor (5 != 5)); // true ?>

Logical NOT (!)

The logical NOT operator, also called negation, is indicated by the sign! . He is unary operator, placed before a single operand. The logical NOT operator is used to invert the logical value of its operand and always returns true or false .

If you need to invert the value of an expression such as a && b , you will need to use round brackets: !(a && b) . Also with the help of an operator! You can convert any x value to its Boolean equivalent by using the operator: !!x twice.


The main thing is to take action operator data- this condition. if translated from English means If. The condition is accepted as an argument (what is in parentheses). The condition can be a logical expression or a logical variable. To put it simply, the meaning of the expression will be this:

If (condition)(
the condition is met, do this
}
else
{
the condition is not met, do it differently
}
I hope the logic of the conditional operation is clear. Now let's look at an example.

$a = 5;
$b = 25;

// Now attention! Condition: If $b is greater than $a
// Signs > and< , как и в математике, обозначают больше и меньше
if($b > $a)
{
// if the condition is met, then perform this action
echo "$b is greater than $a";
}
else
{
// if not executed, then this
echo "$a is greater than or equal to $b";
}
?>
Demonstration Download sources
As a result, the script will output 25 more than 5. The example is quite simple. I hope everything is clear. Now I propose to consider a more complicated situation, where several conditions must be met. Each new condition will contain after the main condition if()- auxiliary, which is written as else if(). In the end it will be as usual else.

Task: Testing is carried out at school. The script needs to calculate the score, knowing the conditions for obtaining each grade and the student’s score itself. Let's see how to write this, and don't forget to read the commentary.

$test = 82; // let's say a student wrote a test with 82 points

// write the first condition for five
if($test > 90)
{
// if the condition is met, then perform this action.
echo "Rating 5";
}
// The && sign means "and, union", that the condition is met if both are true
// that is, the score is less than 91 and more than 80, then 4. Otherwise, the conditions are read further
else if ($test< 91 && $test > 80)
{
echo "Rating 4";
}
else if ($test< 81 && $test > 70)
{
echo "Rating 3";
}
else
{
echo "We should write the test again...";
}
?>
Demonstration Download sources
Our student who has time to both rest and write a normal test gets rating 4! I hope the principle of operation is clear.

It is also possible to briefly record the operation of a conditional operation, when you need an action only if the condition is met.

$age = 19; // variable with age

If ($age > 17)(
echo "That's it! I can do whatever I want! I'm already $age!";
}
Quite a nice example short note conditional operation. else it is not necessary to write.

Comparison Operators in PHP

The principle of operation of a conditional operation is clear. But, as you understand, there are many more ways to compare. Let's look at the table below with comparison operators.

Example Name Result
$a == $b Equals True if $a equals $b
$a === $b Identical to True if $a is equal to $b and both variables are of the same type
$a != $b Not equal to True if $a is not equal to $b
$a === $b Not identical to True if $a is not equal to $b and both types are not the same
$a > $b Greater than True if $a is greater than $b
$a< $b Меньше чем True, если $a меньше, чем $b
$a >= $b Greater than or equal to True if $a is greater than or equal to $b
$a<= $b Меньше или равно True, если $a меньше или равно $b
Now let's look at the operators with examples:

// contrary to habit = means assigning a value to a variable, and == is equal
if ($a == 5)(
echo "$a is 5"; // will print "5 equals 5"
) else (
echo "$a is not equal to 5";
}

If ($a != 6)(
echo "$a is not equal to 6"; // will print "5 is not equal to 6". Necessary in case of denial
) else (
echo "$a somehow equals 6";
}

// with more and less I think everything is clear. Therefore the example is more complicated
if ($a<= 6){
echo "$a is less than or equal to 6"; // will print "5 is less than or equal to 6"
) else (
echo "$a is greater than 6";
}

PHP Logical Operators

There are times when you need to compare not one variable, but two or more at once in one condition. For this there are logical operators.

Example Name Result
$a and $b Logical "and" TRUE if both $a and $b are TRUE.
$a or $b Logical "or" TRUE if either $a or $b is TRUE.
$a xor $b Exclusive "or" TRUE if $a or $b is TRUE, but not both.
! $a Negation of TRUE if $a is not TRUE.
$a && $b Logical "and" TRUE if both $a and $b are TRUE.
$a || $b Boolean "or" TRUE if either $a or $b is TRUE.
We have already noticed that for operations And And or are there additional operators? This is done in order to prioritize complex comparison operations. In the table, logical operators are listed in order of priority: from least to greatest, that is, for example, || has higher priority than or.

Let's move on to examples

$a = 5;
$b = 6;
$c = 7;

// condition: If 5 is not equal to 6 (TRUE) AND 6 is not equal to 7 (TRUE)
if ($a< 6 && $b != $c){
echo "Indeed so!"; // will print "Indeed so!" because BOTH conditions are TRUE
) else (
echo "One of the conditions is not true";
}

// condition: If 6 is not equal to 6 (FALSE) OR 6 is not equal to 7 (TRUE)
if ($b != 6 || $b != $c)(
echo "That's it!"; // will display "That's it!", because at least ONE of the conditions is TRUE
) else (
echo "Both conditions are false";
}

Ternary operator

I suggest you return to the issue of ternary code later. I couldn’t help but mention it, since it’s an important design that significantly reduces the code size. I suggest you look at the code right away.

The gist of the code:(condition) ? the value of a if true: the value of a if false

Thus, we shorten the if statement. However, this operation is only valid when assigning values ​​to a variable. Now let's look at a finished example.

// Example of using the ternary operator
$settings = (empty($_POST["settings"])) ? "Default" : $_POST["settings"];

// The above code is similar to the following block using if/else
if (empty($_POST["settings"])) (
$settings = "Default"; // If nothing is transferred, then leave it as "Default"
) else (
$settings = $_POST["settings"]; // If passed, then $settings is assigned the passed value.
}
?>
Read the comments to the code and everything should be clear.

Thank you for your attention!


The two main statements that provide conditional branching structures are if and switch. The most widely used if statement is used in conditional jump structures. On the other hand, in certain situations, especially if you have to navigate through one of numerous branches depending on the value of a single expression, and the use of a number of if statements leads to more complex code, the switch statement becomes more convenient.

Before studying these operators, you need to understand logical expressions and operations.

Logical operations

Logical operations allow you to combine logical values ​​(also called truth values) to produce new logical values. As shown in the table below, in PHP language standard logical operators (and, or, not and xor) are supported, with the first two having alternative versions.

PHP Logical Operations
Operation Description
and An operation whose result is true if and only if both of its operands are true
or An operation whose result is true if one of its operands (or both operands) is true
! An operation whose result is true if its single operand (given to the right of the operation sign) is false, and false if its operand is true
xor An operation whose result is true if either of its operands (but not both) is true
&& Same as the and operator, but binds its operands more tightly than this operator
|| Same as the or operator, but binds its operands more tightly than this operator

Operations && and || should be familiar to C programmers. Operation! is usually called not because it becomes the negation of the operand to which it is applied.

To test whether both operands are TRUE, you use the AND operator, which can also be written as a double ampersand (&&). Both operators, AND and &&, are logical, their only difference is that the && operator has more high priority than the AND operator. The same applies to the OR and || operators. The AND operator returns TRUE only if both operands are TRUE; otherwise, FALSE is returned.

To check whether at least one operand is TRUE, you use the OR operator, which can also be written as a double vertical line(||). This operator returns TRUE if at least one of its operands is TRUE.

When using the OR operator in a program, subtle logical errors can appear. If PHP detects that the first operand is TRUE, it will not evaluate the value of the second operand. This saves execution time, but you must be careful to ensure that code that the program depends on to run correctly is not placed in the second operand.

The XOR operator allows you to check whether only one of the operands (but not both) is TRUE. This operator returns TRUE if one and only one of its operands is TRUE. If both operands are TRUE, the operator will return FALSE.

You can invert a Boolean value using the NOT operator, which is often written as exclamation point(!). It returns TRUE if the operand is FALSE and FALSE if the operand is TRUE.

The table below shows some logical expressions and their results:

Comparison Operations

The table below shows comparison operations that can be used with either numbers or strings:

Comparison Operations
Operation Name Description
== Equals An operation whose result is true if its operands are equal and false otherwise
!= Not equal An operation whose result is false if its operands are equal and true otherwise
< Less An operation whose result is true if the left operand is less than the right operand, and false otherwise
> More An operation whose result is true if the left operand is greater than the right operand, and false otherwise
<= Less or equal An operation whose result is true if the left operand is less than or equal to the right operand, and false otherwise
>= More or equal An operation whose result is true if the left operand is greater than or equal to the right operand, and false otherwise
=== Identically An operation whose result is true if both operands are equal and of the same type, and false otherwise

One very common mistake you need to make is not to confuse the assignment operator (=) with the comparison operator (==).

Operation priority

Of course, one should not overuse a programming style in which the sequence of operations is mainly determined by the use of precedence rules, since code written in this style is difficult to understand for those who later study it, but it should be noted that comparison operations have higher priority than logical operations. This means that a statement with a check expression like the one below

PHP code $var1 = 14; $var2 = 15; if (($var1< $var2) && ($var2 < 20)) echo "$var2 больше $var1 но меньше 20";

can be rewritten as

PHP code ...if ($var1< $var2 && $var2 < 20) ...

if-else statement

Instructions if allows a block of code to be executed if the conditional expression in this instruction evaluates to TRUE; otherwise the block of code is not executed. Any expression can be used as a condition, including tests for non-zero value, equality, NULL involving variables and values ​​returned by functions.

It does not matter which individual conditionals make up the conditional sentence. If the condition is true, it is executed program code, enclosed in curly braces (()). Otherwise, PHP ignores it and moves on to checking the second condition, checking all the conditionals you wrote down until it hits the statement else, after which it will automatically execute this block. The else statement is optional.

The syntax of the if statement is:

If (conditional expression) (block of program code;)

If the result of evaluating a conditional expression is TRUE, then the block of program code located after it will be executed. In the following example, if $username is set to "Admin", a welcome message will be displayed. Otherwise nothing will happen:

PHP code $username = "Admin"; if ($username == "Admin") ( echo "Welcome to the admin page."; )

If a block of program code contains only one instruction, then the curly braces are optional, however, good habit– always install them, since they make the code easier to read and edit.

The optional else statement is a block of code that is executed by default when the conditional expression evaluates to FALSE. The else statement cannot be used separately from the if statement because else does not have its own conditional expression. That is, else and if should always be together in your code:

if and else statements $username = "no admin"; if ($username == "Admin") ( echo "Welcome to the admin page."; ) else ( echo "Welcome to the user page."; )

Remember to close a block of code in an if statement with a curly brace if you put a curly brace at the beginning of the block. The else block must also have opening and closing curly braces, just like the if block.

This is all good, except when you need to check several conditions in a row. Instructions are suitable for this elseif. It allows you to check additional conditions until true is found or the else block is reached. Each elseif statement has its own block of code placed immediately after the elseif statement's conditional expression. The elseif statement comes after the if statement and before the else statement, if there is one.

The elseif statement syntax is a little more complicated, but the following example will help you understand it:

Checking multiple conditions $username = "Guest"; if ($username == "Admin") ( echo "Welcome to the admin page."; ) elseif ($username == "Guest") ( echo "Viewing not available."; ) else ( echo "Welcome to the page user."; )

Here two conditions are checked and, depending on the value of the $username variable, different actions. And there is still an opportunity to do something if the value of the variable differs from the first two.

Ternary operator?:

The ?: operator is a ternary (ternary) operator that takes three operands. It works similar to an if statement, but returns the value of one of two expressions. The expression that will be evaluated is determined by the conditional expression. The colon (:) serves as an expression separator:

(condition) ? evaluate_if_condition_true: evaluate_if_condition_false;

The example below checks a value and returns different strings depending on whether it is TRUE or FALSE:

Creating a message using the ? operator: $logged_in = TRUE; $user = "Igor"; $banner = (!$logged_in) ? "Register!" : "Welcome back, $user!"; echo $banner;

It is quite obvious that the above statement is equivalent to the following statement:

PHP code $logged_in = TRUE; $user = "Igor"; if (!$logged_in) ( $banner = "Register!"; ) else ( $banner = "Welcome back, $user!"; ) echo $banner;

switch statement

Instructions switch compares an expression with multiple values. As a rule, a variable is used as an expression, depending on the value of which a particular block of code must be executed. For example, imagine a $action variable that can have the values ​​"ADD", "MODIFY" (change), and "DELETE". The switch statement makes it easy to define the block of code that should be executed for each of these values.

To show the difference between if and switch statements, let's test a variable against multiple values. The example below shows program code that implements such a check based on the if statement, and in the following example, based on the switch statement:

Testing against one of several values ​​(if statement) if ($action == "ADD") ( echo "Perform an addition."; echo "The number of instructions in each block is unlimited."; ) elseif ($action == "MODIFY") ( echo "Perform a change."; ) elseif ($action == "DELETE") ( echo "Perform deletion."; ) Testing against one of several values ​​(switch statement) switch ($action) ( case "ADD": echo "Perform an addition."; echo "The number of instructions in each block is unlimited."; break; case "MODIFY": echo "Perform a change."; break; case "DELETE" : echo "Perform deletion."; break )

The switch statement takes the value next to the switch keyword and begins comparing it with all the values standing nearby with keywords case, in the order of their location in the program. If a match is not found, none of the blocks are executed. Once a match is found, the corresponding block of code is executed. The code blocks below are also executed - until the end of the switch statement or until keyword break. This is convenient for organizing a process consisting of several successive steps. If the user has already completed some steps, he will be able to continue the process from where he left off.

The expression next to the switch statement must return a value of a primitive type, such as a number or string. An array can only be used as a separate element that has a value of an elementary type.

Default selection

If the value of the conditional expression does not match any of the options proposed in the case statements, the switch statement in this case allows you to do something, much like the instruction else constructs if, elseif, else. To do this, you need to make an instruction as the last option in the selection list default:

Creating an Error Message Using the Default Statement $action = "REMOVE"; switch ($action) ( case "ADD": echo "Perform an addition."; echo "The number of instructions in each block is unlimited."; break; case "MODIFY": echo "Perform a change."; break; case "DELETE" : echo "Perform deletion."; break; default: echo "Error: $action command is not valid, ". "Only ADD, MODIFY and DELETE commands can be used.";

In addition to the usual one, the switch statement supports an alternative syntax - a keyword construction switch/endswitch, defining the beginning and end of the statement instead of curly braces:

The switch statement ends with the keyword endswitch switch ($action): case "ADD": echo "Perform adding."; echo "The number of instructions in each block is unlimited."; break; case "MODIFY": echo "Perform modification."; break; case "DELETE": echo "Perform deletion."; break; default: echo "Error: $action command is not valid, ". "Only the ADD, MODIFY and DELETE commands can be used."; endswitch;

Interrupt execution

If only the block of code corresponding to a certain value, then the break keyword should be inserted at the end of this block. PHP interpreter, upon encountering the break keyword, will proceed to execute the line located after the closing curly brace of the switch statement (or the endswitch keyword). But if you do not use the break statement, then the check continues in subsequent case branches of the switch construct. Below is an example:

What happens in the absence break statements $action="ASSEMBLE ORDER"; switch ($action) ( case "ASSEMBLE ORDER": echo "Assemble order.
"; case "PACKAGE": echo "Pack.
"; case "SHIP": echo "Deliver to the customer.
"; }

If the $action variable is set to "ASSEMBLE ORDER", the result of this fragment will be as follows:

Collect the order. To wrap up. Deliver to the customer.

Assuming that the build stage has already been completed and the $action variable is set to "PACKAGE", the following result will be obtained:

To wrap up. Deliver to the customer.

Sometimes, not having a break statement is useful, as in the example above where the order stages are formed, but in most cases this statement should be used.

Data types Cycles 1 2 3 4 5 6 7 8 9 10