RUVIDEO
Поделитесь видео 🙏

Operator Precedence - PHP - P23

Operator precedence just looks at which operation will be performed first. You’ve seen operator precedence in mathematics. The multiplication and division operators are executed before the addition and subtraction operators. With all of the different operators that we have in PHP, the interpreter needs to know which operation to perform in what order.

Let’s look at a basic example in math to get started:

2 + 3 * 5

If you were not aware of operator precedence in mathematics, you may start working from left to right. The answer that you would get would be incorrect: 25. However, we all took math and we know that multiplication comes before addition, so we get 17.

You don’t have to know the precedence of each operator: you can always look it up if you encounter something strange. However, the ones you should be familiar with are the following:

new
** (exponential)
++ -- (increment/decrement)
! (logical not)
* / % (arithmetic)
+ - . (arithmetic/concatenation)
== != === !== GT LT Spaceship (comparison)
&& (logical)
|| (logical)
?: (ternary)
= += -= *= /= %= (assignment)
and (logical)
xor (logical)
or (logical)

Why does operator precedence matter so much? You already know which operations will be separate in mathematics, so what’s the big deal? The time that it might cause you the most amount of issue is during logical operations.

Let’s take a look at the following example:

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

If we worked from left to right, we might evaluate the expression as follows

true || !true
true || false = true
true && false = false

The result that you get is false. In order for the OR (||) operator to be true, either the left or the right side has to be true (or both). Since the left side is true, the overall expression is true. For the AND (&&) operator to return true, both sides have to be true. Since the right side is false, the overall expression is false.

Of course we received the wrong result. Let’s take a look at the result when we factor in operator precedence. The operators in the expression above are !, &&, and ||. The ! operator has the highest precedence, followed by &&, and finally finishing up with the || operator. So let’s see what that looks like.

!true && false
false && false = false
true || false = true

This time we get true. Following operator precedence is important. If we wanted to achieve the result that we achieved in the first example, we would have to use parentheses.

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

When we use parentheses, we’re telling PHP to do that operation first. This time we get false.
One thing to note is the && operator. The way the && operator works is that it looks at the expression on the left, and if it’s false, it won’t even look at the expression on the right. PHP programmers don’t do this too often, but I’ve seen programmers in other programming languages use this too their advantage, and sometimes to their disadvantage. If you’ve done any type of programming using JavaScript’s React library, you’ll quickly notice that programmers like to take advantage of this fact. If the expression on the left evaluates to true, execute some content on the right. This is called conditional rendering in React.

Read the full article on my website
https://www.dinocajic.com/php-operator-precedence/

Code for this tutorial
https://github.com/dinocajic/php-7-youtube-tutorials/blob/master/23%20Operator%20Precedence.php

Full Code
https://github.com/dinocajic/php-7-youtube-tutorials

PHP Playlist
https://www.youtube.com/playlist?list=PLbhJy0VhR6SAmoneYvF6Y_axQJKg7i50M

--
Dino Cajic
Author and Head of IT

Homepage: https://www.dinocajic.com
GitHub: https://github.com/dinocajic
Medium: https://medium.com/@dinocajic
Instagram: https://www.instagram.com/think.dino
LinkedIn: https://www.linkedin.com/in/dinocajic/
Twitter: https://twitter.com/dino_cajic

My Books
An Illustrative Introduction to Algorithms
https://www.amazon.com/dp/1686863268

Laravel Excel: Using Laravel to Import Data
https://amzn.to/4925ylw

Code Along With Me - PHP: From Basic to Advanced PHP Techniques
https://amzn.to/3M6tlGN

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Operator Precedence - PHP - P23», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.