Conditional statements. Operations in PHP


Last update: 1.11.2015

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

Arithmetic operations

    + (addition operation)

    For example, $a + 5

    - (subtraction operation)

    For example, $a - 5

    * (multiplication)

    For example, $a * 5

    / (division)

    For example, $a / 5

    % (obtaining the remainder of division)

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

    ++ (increment/increase value by one)

    For example, ++$a

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

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

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

    -- (decrement/decrease value by one)

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

Assignment Operators

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

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

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

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

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

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

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

Comparison Operations

Comparison operations are usually used in conditional 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 logical operations are available:

    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.

The lesson will cover conditional php statements: the if statement and the switch statement

Conditional statements php are represented by three main structures:

  • 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 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: 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 ;

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 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!


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, here's next 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 evaluation with its left operand; if it returns true, then the right operand will not be evaluated. This saves execution time, but you must be careful to ensure that code that may depend on correct work program was not placed in the right operand.

Logical AND (AND and &&)

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

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

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

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

$bar3"; // => 9 ?>

Exclusive OR (XOR)

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

Since the priority of the XOR operator is the same as AND operators and OR (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! . It is a 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.







2024 gtavrl.ru.