You get a bonus - 1 coin for daily activity. Now you have 1 coin

PHP operators

Lecture



PHP operators

" General information about PHP statements
" PHP arithmetic operators
" PHP logical operators
" PHP string operators
" PHP bitwise operators
" PHP assignment statements
" PHP comparison operators
" PHP increment and decrement operations
" PHP equivalence operators
" Operations with PHP character variables
" Priority PHP Operators
" PHP Execution Operators
" Array Operators
" PHP error management statements
" PHP class operators

PHP operators. General information

There are various groups for performing operations with variables. operators .

The operator is called something consisting of one or more values ​​(expressions, if we speak in the jargon of programming), which can be calculated as a new value (thus, the whole structure can be considered as an expression). It follows that functions or any other constructions that return a value (for example, print () ) are operators, unlike all other language constructs (for example, echo () ), which do not return anything.

You can familiarize yourself with all PHP statements below.

PHP arithmetic operators

Remember school basics of arithmetic? The PHP statements described below work the same way.

Example Title Result
- $ a Negation Change sign $ a.
$ a + $ b Addition The sum of $ a and $ b.
$ a - $ b Subtraction Difference $ a and $ b.
$ a * $ b Multiplication The product of $ a and $ b.
$ a / $ b Division Quotient from dividing $ a by $ b.
$ a% $ b Modulo The integer remainder of dividing $ a by $ b.
$ a ** $ b Exponentiation The result is $ a to the power of $ b. (appeared in PHP 5.6.0)

A division operation ("/") always returns a real type, even if both values ​​were integer (or strings, which are converted to integers). Otherwise, the result will be fractional.

The operation of calculating the remainder of the division " % " works only with integers, so applying it to fractional can lead to an undesirable result. The balance of $ a% $ b will be negative for negative values ​​of $ a .

It is possible to use brackets. The priority of some mathematical operations on others and the change of priorities when using brackets in arithmetic expressions correspond to the usual mathematical rules.

PHP logical operators

Logical operators are designed exclusively for working with logical expressions and return false or true .

Here is a table of PHP logical operators:

Example Title Result
$ a and $ b Logical 'and' TRUE if both $ a and $ b TRUE .
$ a or $ b Logical or TRUE if either $ a or $ b TRUE .
$ a xor $ b Exclusive 'or' TRUE if $ a, or $ b TRUE , but not both.
! $ a Negation TRUE if $ a is not TRUE .
$ a && $ b Logical 'and' TRUE if both $ a and $ b TRUE .
$ a || $ b Logical or TRUE if either $ a or $ b TRUE .

The meaning of two different options for the "and" and "or" operators is that they work with different priorities.

It should be noted that the calculation of logical expressions containing such operators always goes from left to right, while if the result is already obvious (for example, false && something always gives false ), then the calculation is terminated even if there are function calls in the expression. For example, in the $logic = 0&&(time()>100); operator $logic = 0&&(time()>100); The standard time () function will never be called.

Be careful with logical operations - do not forget about the double character. Note that, for example, | and || - two completely different operators, one of which can potentially return any number, and the second only false and true .

The increment operators (++) and decrement (-) do not work with logical variables.

PHP string operators

In PHP, there are two operators for working with strings. The first is the concatenation operator ('.'), Which returns the union of the left and right argument. The second is an assignment operator with concatenation, which appends the right argument to the left argument. Let's give a specific example:

<?php
$a = "Hello ";
$b = $a . "World!"; // $b содержит строку "Hello World!"

$a = "Hello ";
$a .= "World!"; // $a содержит строку "Hello World!"
?>

PHP bitwise operators

Bitwise operations are designed to work (set / remove / check) groups of bits in an integer variable. The bits of the integer number are nothing but the individual bits of the same number written in the binary number system. For example, in the binary system the number 12 will look like 1100, and 2 - as 10, so the expression 12 | 2 will return us the number 14 (1110 in binary notation). If the variable is not integer, then it is
The round is rounded, and then the following operators are applied to it.

32 bits are used to represent one number:

  • 0000 0000 0000 0000 0000 0000 0000 0000 is zero;
  • 0000 0000 0000 0000 0000 0000 0000 0001 is 1;
  • 0000 0000 0000 0000 0000 0000 0000 0010 is 2;
  • 0000 0000 0000 0000 0000 0000 0000 0011 is 3;
  • 0000 0000 0000 0000 0000 0000 0000 0100 is 4;
  • 0000 0000 0000 0000 0000 0000 0000 0101 is 5;
  • ...
  • 0000 0000 0000 0000 0000 0000 0000 1111 is 15;
  • ...

Bitwise operators:

Example Title Result
$ a & $ b Bitwise 'and' Only those bits that are set in both $ a and $ b are set.
$ a | $ b Bitwise or Those bits are set that are set to either $ a or $ b.
$ a ^ $ b Exclusive or Only those bits are set that are set either to only $ a, or only to $ b
~ $ a Negation Those bits are set that are not set in $ a, and vice versa.
$ a << $ b Shift left All bits of the $ a variable are shifted by $ b positions to the left (each position implies 'multiplication by 2')
$ a >> $ b Shift right All bits of the $ a variable are shifted by $ b positions to the right (each position implies a 'division by 2')

If both the left and right operands of the string are present, bitwise operations will work with their ASCII representations. Example:

<?php
echo 12 ^ 9; // Выведет '5'

echo "12" ^ "9"; // Отобразит симовол возврата каретки (ascii 8)
// ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" ^ "hello"; // Выведет следующие ASCII-значения: #0 #4 #0 #0 #0
// 'a' ^ 'e' = #4
?>

Note: Do not use a right shift of more than 32 bits on thirty-two bit systems. Do not use the right shift to get numbers that require more than 32 bits to write.

PHP assignment statements

The basic assignment operator is denoted as = . At first glance it may seem that this operator is "equal". In fact, it is not. In fact, the assignment operator means that the left operand gets the value of the right expression, (i.e. set by the resulting value).

The result of the assignment statement is the self-assigned value. Thus, the result of executing $ a = 3 will be equal to 3 . This allows you to use constructions of the form:

<?php

$a = ($b = 4) + 5; // результат: $a установлена значением 9, переменной $b присвоено 4.

?>

In addition to the basic assignment operator, there are "combined operators" for all binary arithmetic and string operations that allow you to use a value in an expression, and then set it as the result of a given expression. For example:

<?php

$a = 3;
$a += 5; // устанавливает $a значением 8, аналогично записи: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // устанавливает $b строкой "Hello There!", как и $b = $b . "There!";

?>

Please note that the assignment copies the original variable to the new one (assignment by value), so all subsequent changes of one of the variables to the other are not reflected in any way. Starting in PHP 4, assignment by reference is also supported using the syntax $var = &$othervar; "Assignment by reference" means that both variables point to the same data and no copying takes place.

PHP comparison operators

Comparison operators, as their name implies, allow us to compare two values ​​with each other.

This is a kind of unique operation, because regardless of the types of their arguments, they always return one of two things: false or true . Comparison operations allow you to compare two values ​​between themselves and, if the condition is satisfied, return true , and if not, false .

In PHP, only scalar variables are allowed to be compared. Arrays and objects in PHP cannot be compared. They cannot even be compared for equality (using the == operator), but when performing such an operation, PHP does not issue a warning. So, being surprised once, why two completely different arrays when comparing them with == turn out to be the same, remember that before comparing both operands are transformed into the word array , which is then compared.

See the comparison of arrays here .

You may also be interested in the section Type Comparison, which contains a large number of relevant examples.

Comparison Operators:

Example Title Result
$ a == $ b Equally TRUE if $ a is $ b.
$ a === $ b Identically equal TRUE if $ a is equal to $ b and has the same type. (Added in PHP 4)
$ a! = $ b Not equal TRUE if $ a is not equal to $ b.
$ a <> $ b Not equal TRUE if $ a is not equal to $ b.
$ a! == $ b Identically not equal TRUE if $ a is not equal to $ b or if they are of different types (Added in PHP 4)
$ a <$ b Less TRUE if $ a is strictly less than $ b.
$ a> $ b More TRUE if $ a is strictly greater than $ b.
$ a <= $ b Less or equal TRUE if $ a is less than or equal to $ b.
$ a> = $ b More or equal TRUE if $ a is greater than or equal to $ b.

In case you compare an integer with a string, the string will be converted to a number. In case you compare two numeric strings, they are compared as integers.

<?php
var_dump(0 == "a"); // 0 == 0 -> true
var_dump("1" == "01"); // 1 == 1 -> true

switch ("a") {
case 0:
echo "0";
break;
case "a": // Эта ветка никогда не будет достигнута, так как "a" уже сопоставленно с 0
echo "a";
break;
}
?>

Another conditional operator is ternary operator " ? ":

<?php
// Пример использования тернарного оператора
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// Приведенный выше код аналогичен следующему блоку с использованием if/else
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>

Expression (expr1)? (expr2): (expr3) is interpreted as expr2 if expr1 evaluates to TRUE , or expr3 if expr1 evaluates to FALSE .

PHP increment and decrement operators

PHP, similar to C, supports the prefix and postfix increment and decrement operators.

Example Title Act
++ $ a Prefix increment Increments $ a by one and returns the value of $ a.
$ a ++ Postfix increment Returns the value of $ a, and then increments $ a by one.
- $ a Prefix decrement Reduces $ a by one and returns $ a.
$ a-- Postfix decrement Returns the value of $ a, and then decrements $ a by one.

Postfix increment and decrement operators

As in C, these operators increase or decrease the value of a variable, and in the expression return the value of the $ a variable before the change. For example:

$a=10;
$b=$a++;
echo "a=$a, b=$b"; // Выводит a=11, b=10

As you can see, first, the variable $ b was assigned the value of the variable $ a , and only then the latter was incremented. However, an expression whose value is assigned to the $ b variable may be more complicated - in any case, the increment of $ a will occur only after its calculation. Such operations are called postfix increment operations.

Prefix increment and decrement operators

There are also increment and decrement operators, which are specified before and not after the variable name. Accordingly, they return the value of the variable after the change. Example:

$a=10;
$b=--$a;
echo "a=$a, b=$b"; // Выводит a=9, b=9

The increment and decrement operations are used very often in practice. For example, they are found in almost any for loop.

<?php
echo "<h3>Постфиксный инкремент</h3>";
$a = 5;
echo "Должно быть 5: " . $a++ . "<br />\n";
echo "Должно быть 6: " . $a . "<br />\n";

echo "<h3>Префиксный инкремент</h3>";
$a = 5;
echo "Должно быть 6: " . ++$a . "<br />\n";
echo "Должно быть 6: " . $a . "<br />\n";

echo "<h3>Постфиксный декремент</h3>";
$a = 5;
echo "Должно быть 5: " . $a-- . "<br />\n";
echo "Должно быть 4: " . $a . "<br />\n";

echo "<h3>Префиксный декремент</h3>";
$a = 5;
echo "Должно быть 4: " . --$a . "<br />\n";
echo "Должно быть 4: " . $a . "<br />\n";
?>

Boolean types are not subject to increment and decrement.

Operations with character variables

<?php
$i = 'W';
for($n=0; $n<6; $n++)
echo ++$i . "\n";

/*
Результат работы будет следующий:

X
Y
Z
AA
AB
AC

*/
?>

Recall once again that incrementing or decrementing Boolean variables does not lead to any result. '

PHP equivalence operators

In PHP, starting with PHP4, there is an identity comparison operator - the triple equal sign === ,
or check operator equivalence . PHP is quite tolerant that strings are implicitly converted to numbers, and vice versa.
For example, the following code will show that the values ​​of the variables are equal:

$a=10;
$b="10";
if($a==$b) echo "a и b равны"; // Выводит "a и b равны"

And this is despite the fact that the variable $ a is a number, and $ b is a string. Let’s look at a slightly different example:

$a=0; // ноль
$b=""; // пустая строка
if($a==$b) echo "a и b равны"; // Выводит "a и b равны"

Although $ a and $ b are clearly not equal even in the usual sense of the word, the script will declare that they are the same. Why it happens? The fact is that if one of the operands of a logical operator can be interpreted as a number, then both operands are treated as numbers. In this case, the empty string turns into 0 , which is then compared to zero. Not surprisingly, the echo statement works.
The problem is solved by the equivalence operator === (triple equality). It not only compares two expressions, but also their types. Rewrite our example using this statement:

$a=0; // ноль
$b=""; // пустая строка
if($a===$b) echo "a и b равны"; // Ничего не выводит

Now nothing will be displayed. But the possibilities of the equivalence operator go far beyond the comparison of simple variables. It can also be used to compare arrays, objects, etc. This is sometimes very convenient. Here is an example:

$a=array('a'=>'aaa');
$b=array('b'=>'bbb');
if($a==$b) echo "С использованием == a=b<br>";
if($a===$b) echo "С использованием === a=b<br>";

If you run the presented code, the first message will be displayed, but not the second one.
This happens because, as we already said, the operands-arrays are converted to strings of the array , which then will be compared. Operator === is deprived of this disadvantage, so it works correctly.
For the === operator, there is its opposite - operator ! ==

Operations with character variables in PHP

PHP follows Perl conventions (as opposed to C) to perform arithmetic operations on character variables. For example, in Perl, 'Z' + 1 will be computed as 'AA' , while in C ', Z' + 1 will be computed as '[' (ord ('Z') == 90, ord ('[') = = 91). It should be noted that the increment operation can be applied to character variables, while the decrement operation cannot be applied.

<?php
$i = 'W';
for($n=0; $n<6; $n++)
echo ++$i . "\n";

/*
Результат работы будет следующий:

X
Y
Z
AA
AB
AC

*/
?>

Priorities for executing statements in PHP

Operator precedence determines how closely the two expressions are related. For example, the expression 1 + 5 * 3 is calculated as 16 , and not 18 , since the multiplication operation ("*") has a higher priority than the addition operation ("+"). If the operators have the same priority, they will be executed from left to right. Parentheses can be used to force the order of statements to be executed. For example, the expression (1 + 5) * 3 is calculated as 18 .

The following table lists the operators, sorted in descending order of priority. Operators placed on the same line have the same priority and their execution order is determined based on their associativity .

Operators with a higher level of priority are executed first:

A priority
Operator
Execution order
13
(postfix) ++ (postfix) -
from left to right
12
++ (prefix) - (prefix)
from right to left
eleven
* /%
from left to right
ten
+ -
from left to right
9
<< >>
from left to right
eight
<<=>> =
from left to right
7
==! =
from left to right
6
&
from left to right
five
^
from left to right
four
|
from left to right
3
&&
from left to right
2
||
from left to right
one
= + = - = * = / =% = >> = << == & = ^ = | =
from right to left

Example of the order of execution of operators (associativity):

<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>

In any case, if in doubt, or afraid to make a mistake, use parentheses. It will also make your code more readable.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)