Chat in Telegram

PHP Operators

15.09.2021 at 13:43
23
0

Operators are one of the most important and basic topics. Almost all expressions contain them in one way or another. Without operators, PHP would not be able to do anything with data at all, just like, for example, in mathematics. Therefore, take this topic seriously, and at the end, be sure to do your homework - only practice, only hardcore.

But before moving on to exploring operators, I suggest looking at the var_dump () function. It allows you to infer the type and value of something.

For example, expressions:

<?php
var_dump(5/2);

Result:

float 2.5

Or a variable:

<?php
$result = 2 < 4;
var_dump($result);

Result:

boolean true

2 is less than 4. The result is true. That's all right.

Congratulations, now at any time we can find out what is in a variable, or immediately find out the result of an expression. Let's now get back to our main topic of the tutorial.

The topic of operators is very closely intertwined with the topic of data types. As we already said in previous lesson, the data type that will result from any expression will depend on the operator. And, for example, the result of addition when using the plus operator will always be a number.

Operator Priority

Let's start with the fact that the operators have different precedence. As, for example, in mathematics: the multiplication operator will take precedence over the addition operator:

<?php
$result = 2 + 2 * 2;
var_dump($result);

Result:

int 6

The priority can be controlled using parentheses, for example:

<?php
$result = (2 + 2) * 2;
var_dump($result);

Well, here I think everything is clear:

int 8

In general, operator priorities are fairly predictable.
The precedence of all operators in PHP can be found in the [official documentation] (http://php.net/manual/ru/language.operators.precedence.php).

Operator types in PHP

Now let's look at the different types of operators.

Arithmetic Operators

Operators familiar from school are waiting for us here:

<?php

$a = 6;
$b = 3;

// Addition
var_dump($a + $b);

// Subtract
var_dump($a - $b);

// Multiplication
var_dump($a * $b);

// Division
var_dump($a / $b);

// Remainder of the division
var_dump($a % 4);

// Exponentiation
var_dump($a ** 2);

Result:

int 9
int 3
int 18
int 2
int 2
int 36

Many fall into a stupor from the remainder operator. Everything is simple here. In our case, we calculate the remainder after dividing 6 by 4. It is not divisible at all, the integer part is 1, and 2 is the remainder. A few more similar examples for understanding:

<?php
var_dump(5 % 2);
var_dump(17 % 12);
var_dump(8 % 4);

Result:

int 1
int 5
int 0

I think arithmetic operators no longer require further clarification.

Assignment Operator

We have already worked with him. Used to assign a value to a variable.
A classic example:

<?php
$a = 55;

Ok, everything is simple here. How about this:

<?php
$result = ($x = 5) * 2;

Here the variable $x was assigned the value 5, and then multiplied by 2 and put the result of the expression in the variable $result. Yes, this is also possible in PHP, although it is not encouraged, since the code looks rather convoluted.

In addition, there are so-called shorthand, combined assignment operators.
For example, in combination with the addition operator:

<?php

$x = 5;
$y = 7;

$y += $x;

var_dump($y);

Result:

int 12

Expression

$y += $x

could be written as

$y = $y + $x

Thus, if something happens to the left operand in its original form, then you can use these shorthand options. And yes, it does apply and looks very elegant, it's worth getting used to now. Let's look at a few more examples:

<?php

$x = 6;
$y = 3;

$x /= $y;

var_dump($x);

Result:

int 2

And with string concatenation:

<?php

$hello = 'Hello ';

$hello .= 'world!';

var_dump($hello);

Result:

string 'Hello world!' (length=12)

Ok, let's move on.

Comparison Operators

Well, here from the name it is clear what these operators are and what they are intended for. Their work will always result in a boolean value (true or false).

Let's start with the equality/inequality operators:

<?php

$x = 2;
$y = '2';

var_dump($x == $y); //equal
var_dump($x === $y); //identical
var_dump($x != $y); //not equal
var_dump($x !== $y); //not identical

Result:

boolean true
boolean false
boolean false
boolean true

Let me explain. Operator == casts operands to the same type and then compares their values. So the string '2' was converted to a number and the values were equal.
The identity operator === does not perform type casts and compares first that the types of the values are identical, such as integers, and then compares their values. And if they are the same, then only in this case it returns true.

For example:
<?php

$x = 2;
$y = 2;

var_dump($x === $y);


Result:
> boolean true

The inequality operator **!=** casts types to one and compares values. If they are not equal, it will return true, otherwise - false.
The operator of identical inequality **!==** first compares the types, if they are not identical, for example, string and number, then it will return true, otherwise it will compare their values. If they are not equal, it will return true, otherwise - false.

Comparison operators also include:

<?php

$x = 2;
$y = 4;

var_dump($x > $y); // $x is greater than $y
var_dump($x < $y); // $x is less than $y
var_dump($x >= $y); // $x is greater than or equal to $y
var_dump($x <= $y); // $x is less than or equal to $y


Result:
> boolean false
> boolean true
> boolean false
> boolean true

Everything is obvious here, let's not linger.

#### Spaceship
Now let's take a look at the comparison operator, which was introduced in PHP7. This is a spaceship **<=>**. Looks like a Star Wars stormtrooper ship, doesn't it?

This operator has the following logic:
$a <=> $b
If $a> $b, will return 1
If $a == $b will return 0
If $a <$b will return -1

Let's take an example:

<?php

var_dump(2 <=> 4);
var_dump(2 <=> 2);
var_dump(5 <=> 3);


Result:
> int -1
> int 0
> int 1

This operator was introduced for use in sorting functions. We will not raise this topic for now, just know that such an interesting operator appeared in the latest version of PHP.

### Increment and decrement
Often in different algorithms it is necessary to increase and decrease integers by one.
For this, there are special operators for increment and decrement.
The options can be very different:
- $i++ - postfix increment, returns the current value of $i and then increments the value by one
- $i-- - postfix decrement, returns the current value of $i and then decrements the value by one
- ++$ i - prefix increment, first increases the value of $i by one, and then returns the result
- --$i - prefix decrement, first decrements the value of $i by one, and then returns the result

Let's take a look at some simple examples:

<?php

$i = 5;

$x = $i++; // First, the variable $x was assigned the current value of $i (5), then $i was increased by 1 (6)
$y = ++$i; // First, we increase the variable $i by 1 (7), then assign a new value to the variable $y (7)
$z = $i--; // First, $z was assigned the value of $i (7), then decreased $i by 1 (6)

var_dump($x);
var_dump($y);
var_dump($z);
var_dump($i);


Result:
> int 5
> int 7
> int 7
> int 6

With increment and decrement, that's it. Move on.

### Logical operators
Now let's talk about one of the most important types of operators, namely, logical. These operators are used to evaluate conditions. The result of such an operator will always be true or false. In this case, the operands are also true or false.
Let's list them:
- && - logical AND, will return true only if both operands are true
- || - logical OR, will return true if at least one of the operands is true
- ! - NEGATIVE, returns true if the operand is false, and vice versa. It is used when you need to invert a condition, which is often very useful.
- xor - exclusive OR, will return true only if one of the operands is true and the other is false

Let's see an example:

<?php

var_dump(true && true); // true
var_dump(true && false); // false
var_dump(true || true); // true
var_dump(true || false); // true
var_dump(false || true); // true
var_dump(!true); // false
var_dump(!false); // true
var_dump(false xor true); // true
var_dump(true xor true); // false
var_dump(true xor false); // true
var_dump(false xor false); // false


Now let's look at a more interesting example - determine if the number is even and at the same time it is greater than 10. To check for evenness - just take the remainder of division by 2 and compare with zero. If it is 0, then the number is even. Let's write the first calculation:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven); // true


And now the second:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven); // true

$isMoreThan10 = $x > 10;

var_dump($isMoreThan10); // true


It remains to make sure that both conditions are met. Let's use a logical AND:

<?php

$x = 14;

$isEven = $x % 2 == 0;

var_dump($isEven);

$isMoreThan10 = $x > 10;

var_dump($isMoreThan10);

$isEvenAndMoreThan10 = $isEven && $isMoreThan10;

var_dump($isEvenAndMoreThan10);


The calculation could be expressed in one line:

<?php

$x = 14;

$isEvenAndMoreThan10 = $x % 2 == 0 && $x > 10;


However, you must agree that the first option is broken down point by point and is more understandable. I want you to understand. Your code shouldn't take up as little space as possible. It must be understandable. It can be said that it would be very nice if he was boring. It should be easy to read by programmers. In the first case, everything is obvious: we found out that the number is even, that it is more than 10, and decided that both of these conditions are fulfilled simultaneously. This is how the person reading your code should think so.

Also, if the operands are not boolean values, they will be automatically cast to true or false. Let's leave this for self-picking - there will be an item in the homework regarding this remark. Be sure to follow it.

### String concatenation operator
Yes, there is only one operator for strings - to combine them into one: the concatenation operator. It represents a point and its use is as follows:

<?php

$string1 = 'Hello';
$string2 = 'world!';

echo $string1 . ', ' . $string2;



Result:
> Hello world!

This concludes our lesson on operators. Be sure to do your homework, without it you will not go further.
loader
15.09.2021 at 13:43
23
0
Homework
  • Study the official documentation on operator priorities on your own
  • Use the var_dump () function to get the results of the following expressions:
    • !1
    • !0
    • !true
    • 2 && 3
    • 5 && 0
    • 3 || 0
    • 5 / 1
    • 1 / 5
    • 5 + '5string'
    • '5' == 5
    • '05' == 5
    • '05' == '5'
Comments
New comment