PHP logical operators include: Parentheses 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 mark(!). 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 are 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 refer to 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 ;

The main thing in the action of this operator is the 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 it's logic conditional operation understandable. 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!