Conditional statements. PHP Logical Operators



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 receives 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 of a short notation of a 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 lesson will cover conditional statements php: if statement and 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 IF statement, 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 clause and do not contain an additional elseif condition
  • 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 elseif condition, the else clause 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 in parentheses must contain a logical expression or 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 PHP language translator will consider the variable in brackets to be a 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: a variable a with a string value is given. 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 "It's 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 constructions 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 are available logical operations:

    Returns true if both comparisons 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 bitwise 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.

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 a specific action, or operation.

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 anyone needs to, they will have to go through 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 (true), or an empty string, which corresponds to false (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 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

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 operation and, but binds its operands more tightly compared to this operation
|| 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 the AND and && operators are logical operators; the only difference is that the && operator has higher precedence than the AND operator. The same applies to the OR and || operators. 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 the variable $username is set to "Admin", it will print welcome message. 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 curly braces are optional, however, it is a good habit to always use 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 syntax of the elseif statement is a little more complicated, but next 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" (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 starts comparing it with all the values ​​next to the 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 in the form of it individual element, having a value of 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 allowed, ". "only ADD, MODIFY and DELETE commands can be used."; )

In addition to the usual, the switch statement supports alternative syntax– construction of keywords 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 a block of code corresponding to a specific value is to be executed, then the break keyword should be inserted at the end of that block. PHP interpreter, upon encountering the break keyword, will proceed to execute the line located after the closing line curly brace switch statements (or 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






2024 gtavrl.ru.