Php logical operator inversion not. Logical constructs AND OR and NOT in the conditional operator

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, PHP supports standard logical operators (and, or, not, and xor), 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 the code it depends on correct work program was 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 Boolean 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 additional conditions to be tested 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 keyword switch, and starts 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 the 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 else statement of the if, elseif, else construction. 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 when there are no 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

Hello dear novice programmers. Let's continue to study the elements that make up.

In this article we will learn what is php operators. In fact, we have been familiar with some of them almost since childhood, but we only know them as signs (+, -, =, !, ?).

In php they are all called operators, which is quite logical, since they perform specific action, or surgery.

You could even say that all printable characters that are not a letter or a number are operators in PHP. But that’s not all, since there are operators consisting of letters.

Let's start in order.

Arithmetic operators

Arithmetic operators are used to perform operations on numbers.

+ is the addition operator;
— — subtraction operator;
/ - division operator;
* — multiplication operator;
% is the operator for obtaining the remainder during division;
++ — operator for increasing by one (increment);
— — — decrease by one operator (decrement)

When writing, a space is usually placed before and after the operator. This is done solely for ease of reading the code, although this space does not affect anything, and you can do without it if you wish.

Complex expressions are composed according to the rules accepted in arithmetic, that is, multiplication and division have priority over addition and subtraction, and when both are present in the expression, the latter are enclosed in parentheses.

echo (6 + 7 ) * (7 + 8 ); // 195
?>

When performing an action, dividing an integer by an integer, in case of obtaining a remainder, the result is automatically converted to real number(floating point number).

echo 8 / 3 ; //2.66666666666
?>

Number of characters displayed for fractional number, depends on set value in the precision directive found in the php.ini file. Usually this is 12 characters not counting the period.

The % operator is commonly used to determine whether one number is divisible by another without a remainder or not.

echo 53328 % 4 ; //0
?>

Operations with arithmetic operators, with the exception of increment and decrement, are called binary, since they involve two operands (term + term, dividend / divisor, etc.)

The actions of increment and decrement are called unary, since they involve one operand. Is there some more conditional operation, which involves three operands.

The increment (++) and decrement (- -) operators apply only to variables.

Variable type integer (whole numbers)

$next = 3 ;
echo +$next; // 4
?>

Variable type string

$next = "abc";
echo $next; // abd
?>

The letter "d" is printed instead of the letter "c" because it is next in the alphabet and we increased the value of the variable by one.

The examples show actions with increment, and in the same way you can perform actions with decrement.

Bitwise operators

Bitwise operators are designed to work with binary data. If anyone has no idea what it is, I’ll explain. Binary numbers are numbers like 1001000011100000111000.

Since such data is almost never used in website development, we will not dwell on it in detail. I’ll just show you what they look like, so that when you encounter such symbols you can imagine what you’re dealing with.

& - bitwise connection AND (and);
~ — bitwise negation (not);
| — bitwise union OR (or);
^ — bitwise elimination OR (xor);
<< — сдвиг влево битового значения операнда;
>> — shift to the right the bit value of the operand;

It is quite likely that you will encounter these operators, since binary data is widely used in the development of software programs. computer graphics. But to study them, if someone needs it, they will have to take a separate course on another resource.

Comparison Operators

Comparison operators are logical operators and are used to compare variables. Arrays and objects cannot be compared using them.

> - operator greater than;
=> - greater than or equal operator;
< — оператор меньше;
<= — оператор меньше или равно;
== — equality operator;
!= — inequality operator;
=== — equivalence operator (the value and type of the variable are equal);
!== — non-equivalence operator;

As a result of the comparison, either one is displayed on the screen, which corresponds to true, or an empty string, which corresponds to false.

echo 1 > 0 ; // 1
echo 1< 0 ; // пустая строка
echo 1 => 0 ; // 1
echo 1 == 1 ; // 1
?>

So, by themselves, comparison operators are almost never used. Their main purpose is to work in conjunction with the if statement.

Conditional statements if, else, elseif.

Conditional operators are so called because they are designed to test a certain condition, depending on which a particular action is performed.

The if statement takes a boolean variable, or expression, as an argument. If the condition is true, the result is displayed, if not true, an empty line is displayed.



if ($next< $nexT)
{
echo "Chance of precipitation"; // Output Precipitation possible
}
?>

$next = "Air humidity 80%";
$nexT = "Air humidity 90%";
if ($next > $nexT)
{
echo "Chance of precipitation"; // Print an empty line
}
?>

If the program needs to specify two actions, one of which will be performed if the value is true, and the other if the value is false, then together with the if statement, the else statement is used

$next = "Air humidity 80%";
$nexT = "Air humidity 90%";
if ($next > $nexT)
{
echo "Chance of precipitation";
}
else
{
echo "No precipitation expected";
}
?>

In this case, “Precipitation is not expected” will be displayed, and if in the expression you change the sign “More” to “Less”, then “Precipitation is possible” will be displayed. This is how conditional operators check a condition and output the correct result according to it.

Very often there is a need to set more than two conditions, and then, to check them sequentially, the elseif operator is used.



if ($next > $nexT)
{
echo "I see";
}
elseif ($next<= $nexT)
{
echo "Snow";
}
elseif ($next >= $nexT)
{
echo "Rain";
}
elseif ($next == $nexT)
{
echo "Drought";
}
else
{
echo "Chance of precipitation";
}
?>

This program will output "Snow". If none of the conditions matched, it would display “Chance of Precipitation.”

An if statement can contain as many elseif blocks as you like, but only one else statement.

Allowed Alternative option entries - without curly braces. In this case, the lines of the if, else, elseif statements end with a colon, and the entire construction ends with the keyword (operator) endif.

$next = "Air humidity 50%";
$nexT = "Air humidity 60%";
if ($next<= $nexT):

echo "Snow";

elseif ($next >= $nexT):

echo "Rain";

elseif ($next == $nexT):

echo "Drought";

else:

echo "Chance of precipitation";
endif ;
?>

Logical operators

Logical operators are similar to bitwise operators. The difference between them is that the former operate with logical variables, and the latter with numbers.

Logical operators are used in cases where you need to combine several conditions, which will reduce the number of if statements, which in turn reduces the likelihood of errors in the code.

&& - connecting conjunction AND;
and - also AND, but with lower priority;
|| - separating conjunction OR;
or - also OR, but with lower priority;
xor - exclusive OR;
! - denial;

Lower priority means that if both operators are present, the one with higher priority is executed first.

In the future, using examples of more complex scripts, we will dwell on logical operators in more detail.

Assignment operator

The assignment operator = assigns the value of the right operand to the left operand.

$next = "Hello"
echo "Hello" // Hello
?>

Operator dot

The dot operator separates the integer part of a number from the fractional part, and combines several strings and a number into one whole string.

$next = 22 ;
echo "Today after" .$next. "frost is expected"; // Today after 22:00 frost is expected
?>

Parentheses operator

As in mathematics, the parentheses operator gives priority to the action enclosed within them.

The data enclosed in parentheses is executed first, and then all the rest.

Curly braces operator

There are three ways, or even styles, of placing curly braces in PHP.

1. BSD style - brackets are aligned to the left.

if ($next)
{

}

2. GNU style - brackets are aligned indented from the left edge

if ($next)
{
echo “Hello dear beginning programmers”;
}

3. K&R style - parenthesis opens on the operator line

if ($next)(
echo “Hello dear beginning programmers”;
}

From the very beginning, you need to choose one of the styles and in the future, when writing scripts, use only it. Moreover, it doesn’t matter at all which style you prefer. It is important that it be uniform throughout the program.

I think that's enough for now. In principle, not only signs, but also functions and other elements can be operators, so it is very difficult to list them all, and there is no point.

It is enough to have an idea of ​​the basic basics. And we will analyze the rest using practical examples.

An Irishman wanders around Sheremetyevo Airport in tears. One of the employees decided to sympathize:
— Do you miss your homeland?
- Not at all. I just lost all my luggage
- How could this happen?
- I don’t understand myself. Looks like I plugged the plug properly

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 care must be taken to ensure that code on which the correct operation of the program may depend is not placed in the right-hand 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 parentheses: !(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 lesson will cover conditional php statements: the if statement and the switch statement

PHP conditional statements are represented by three main constructs:

  • condition operator if,
  • switch operator switch
  • And ternary operator.

Let's take a closer look at each of them.

PHP if statement

Figure 3.1. Conditional operator IF, short version


Rice. 3.2. IF ELSE Conditional Statement Syntax


Rice. 3.3. Full syntax of the IF elseif conditional statement

Let's summarize:

Full syntax:

if (condition) ( // if the condition is true operator1; operator2; ) elseif(condition) ( operator1; ... ) else ( // if the condition is false operator1; operator2; )

  • The shortened syntax can do not contain parts of the else construct and do not contain additional condition elseif
  • Instead of the function word elseif, you can write else if (separately)
  • There can be several elseifs in one if construct. The first elseif expression equal to TRUE will be executed.
  • If there is an alternative condition elseif else construct must come last in the syntax.

A conditional statement can use a colon: instead of curly braces. In this case, the statement ends with the auxiliary word endif

Rice. 3.4. Conditional statement If and Endif in php

Example:

if($x > $y): echo $x." is greater than ".$y; elseif($x == $y): // when using ":" you cannot write separately else if echo $x." equals ".$y; else: echo $x." not > and not = ".$y; endif;

Important: When using a colon instead of curly braces in a construction, elseif cannot be written in two words!

Logical operations in a condition

The if condition in parentheses may contain the following operations:

Example: check the value of a numeric variable: if it is less than or equal to 10, display a message "a number less than or equal to 10", otherwise display a message "a number greater than 10"


Solution:

$number=15; if ($number<=10) { echo "число меньше или равно 10"; } else { echo "число больше 10"; }

PHP code blocks can be broken, let's look at an example:

Example: Display html code on screen "a equals 4", if the variable $a is really equal to 4


1 Solution:
1 2 3 4

2 Solution:

1 2 3 A equals 4

A equals 4

php job 3_1: Output color translations from in English into Russian, checking the value of the variable (in which the color is assigned: $a="blue")


php job 3_2: Find the maximum of three numbers

Comparison operations and the lie rule

The if construct must contain in parentheses logical expression or a variable, which is considered from the point of view of the algebra of logic, returning the values ​​​​either true or false

Those. a single variable can act as a condition. Let's look at an example:

1 2 3 4 $a = 1 ; if ($a) ( echo $a; )

$a=1; if ($a) ( echo $a; )

In the example, the translator php language will consider the variable in parentheses for the lie rule:

Rule of LIE or what is considered false:

  • logical False
  • whole zero ( 0 )
  • real zero ( 0.0 )
  • empty line and string «0»
  • array with no elements
  • object without variables
  • special type NULL

Thus, in the considered example, the variable $a is equal to one, accordingly the condition will be true and the operator echo $a; will display the value of the variable.

php job 3_3: given variable a string value. If a is equal to the name, then print "Hello, name!", if a is equal to an empty value, then output "Hello Stranger!"

Logical constructs AND OR and NOT in the conditional operator

  1. Sometimes it is necessary to provide for the fulfillment of several conditions simultaneously. Then the conditions are combined logical operator AND — && :
  2. $a=1; if ($a>0 || $a>1) ( echo "a > 0 or a > 1"; )

  3. To indicate if a condition is false, use logical operator NOT — ! :
  4. 1 2 3 4 $a = 1 ; if (! ($a< 0 ) ) { echo "a не < 0" ; }

    $a=1; if (!($a<0)) { echo "a не < 0"; }

Switch operator PHP

The switch operator or “switch” replaces several consecutive if constructs. In doing so, it compares one variable with multiple values. Thus, this is the most convenient means for organizing multi-branching.

Syntax:

1 2 3 4 5 6 7 8 9 10 switch ($variable) ( case "value1" : operator1 ; break ; case "value2" : operator2 ; break ; case "value3" : operator3 ; break ; [ default : operator4 ; break ; ] )

switch($variable)( case "value1": operator1; break; case "value2": operator2; break; case "value3": operator3; break; )

  • The operator can check both string values ​​(then they are specified in quotes) and numeric values ​​(without quotes).
  • The break statement in the construction is required. It exits the construct if the condition is true and the operator corresponding to the condition is executed. Without break, all case statements will be executed regardless of their truth.

Rice. 3.5. Conditional Switch statement


Example: an array with full male names is given. Check the first element of the array and, depending on the name, display a greeting with a short name.


Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 $names = array ("Ivan" , "Peter" , "Semyon" ) ; switch ($names [ 0 ] ) ( case "Peter" : echo "Hello, Petya!" ; break ; case "Ivan" : echo "Hello, Vanya!" ; break ; case "Semyon" : echo "Hi, Vanya! " ; break ; default : echo "Hi, $names!"; break ; )

$names=array("Ivan","Peter","Semyon"); switch($names)( case "Peter": echo "Hello, Petya!"; break; case "Ivan": echo "Hello, Vanya!"; break; case "Semyon": echo "Hello, Vanya!"; break ; default: echo "Hello, $names!"; break )

php job 3_4:

  • Create a $day variable and assign it an arbitrary numeric value
  • Using the switch construct, print the phrase "It's a work day", if the value of the $day variable falls within the range of numbers from 1 to 5 (inclusive)
  • Print the phrase "It's a day off", if the value of the variable $day is equal to the numbers 6 or 7
  • Print the phrase "Unknown Day", if the value of the $day variable does not fall within the range of numbers from 1 to 7 (inclusive)

Complete the code:

1 2 3 4 5 6 7 8 9 10 11 12 ... switch (... ) ( case 1 : case 2 : ... echo "It's a work day"; break ; case 6 : ... default : ... )

Switch(...)( case 1: case 2: ... echo "This is a working day"; break; case 6: ... default: ... )

PHP ternary operator

Ternary operator, i.e. with three operands, has a fairly simple syntax in which to the left of the ? the condition is written, and on the right are two operators separated by the sign: , to the left of the sign the operator is executed if the condition is true, and to the right of the sign: the operator is executed if the condition is false.

condition? operator1 : operator2 ;

Last update: 11/1/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. The following comparison operations are available.

    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.