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

PHP variable operations (operators) Expressions in PHP

Lecture



To exercise operations with variables there are different groups 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.

PHP arithmetic operations

Remember school basics of arithmetic? The operators 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 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.

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.

Increment and Decrement Operations

PHP, like 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.

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.

Assignment operations

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. Details about the links you can find here .

String operations

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

See also: Assignment Operations

Bitwise operations

These operations are designed to operate (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')

Comparison operations

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 .

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.

Logical operations

Logical operators are designed exclusively for working with logical expressions and also 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 .

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.

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. Now consider 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 also its antipode - the operator ! ===

Operations with character variables

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

*/
?>

PHP statement priorities

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

In any case, if in doubt, or afraid to make a mistake, use brackets.

Expressions - this is the cornerstone of PHP. Almost everything you write in PHP is an expression. Expressions are the "building blocks" of which PHP-programs consist. An expression in PHP is understood to mean what matters. And back: if something matters, then this “something” is an expression.

The main forms of expressions are constants and variables. For example, if you write $ a = 100, you assign $ 100 to $ a:

$a = 100;

In the example above, $ a is a variable, = is an assignment operator, and 100 is expressions. Its value is 100.

An expression can also be a variable if it is associated with a specific value:

$x = 7;
$y = $x;

In the first line of the considered example, the expression is a constant 7, and in the second line is the variable $x , since it was previously assigned the value 7. $y = $x also an expression.

A bit more complicated examples of expressions are functions. For example, consider the following function:

<?php
function funct ()
{
return 5;
}
?>

Assuming that you are familiar with the concept of functions (if not, read the section on user-defined functions), you think that $ x = funct () is absolutely equivalent to $ x = 5 , and you are right. Functions are expressions whose value is what the function returns. Because funct () returns 5, the value of the expression 'funct ()' is 5. As a rule, functions return not a static value, but a calculated one.

PHP supports three types of scalar values: integer, floating point, and string values ​​(scalar values ​​are values ​​that you cannot 'split' into smaller parts, unlike, for example, arrays). PHP also supports two combined (non-scalar) types: arrays and objects. Each of these types of values ​​can be assigned to a variable or returned by a function.

PHP is an expression-oriented language and treats almost everything as an expression. Let us return to the example with which we have already dealt: '$ x = 7'. It is easy to notice that there are two values ​​here - the value of the integer constant '7' and the value of the variable $ x, also taking the value 7. But in fact there is one more value - the value of the assignment itself. The assignment itself is calculated to the assigned value, in this case, to 7. In practice, this means that '$ x = 7', regardless of what it does, is an expression with value 7. Thus, the entry '$ y = ( $ x = 7) 'is equivalent to writing' $ x = 5; $ y = 5; ' (a semicolon indicates the end of an expression). Since assignment operations are analyzed from right to left, you can also write '$ y = $ x = 7'.

Boolean expressions

Logical expressions are expressions that can have only two values: false and true (or, almost the same, 0 and 1). However, more strictly speaking, absolutely any expression can be considered as logical in a “logical” context (for example, as a condition for an if-else construction ). After all, any non-zero number, non-empty string, etc., can be TRUE (true), and FALSE (false) means everything else.
For logical expressions, all properties of logical variables are valid. These expressions most often occur when using the operators > , < and == (equal), || (logical OR), && (logical AND) ,! (logical NOT) and others. For example:

$a = 10 < 5; // $a = false
$a = $b==1; // $a=true
$a = $b >= 1&& $b <= 10; // $a = true, если $b в пределах от 1 до 10
$a = !($b || $c) && $d; // $a = true, если $b и $c ложны, а $d — истинно

How is a truth variable checked? Just like any logical expression:

$b = $a >= 1 && $a <= 10; // присваиваем $b значение логического выражения
if($b) echo "a в нужном диапазоне значений";

Read more about logical operations here.

String expressions

PHP strings are one of the most basic objects. They can contain text along with formatting characters or even binary data.
The definition of a string in quotes or apostrophes can begin on one line and end in another. Here is an example of a string expression:

$a = "Это текст";


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)