Home >Backend Development >PHP Tutorial >PHP operator precedence please explain

PHP operator precedence please explain

WBOY
WBOYOriginal
2016-08-04 09:20:23983browse

After reading the PHP operator precedence, I can understand the examples in the manual, but this one is a bit hard to understand

<code>
echo "1+5". 1+5;// 6

echo "1+5". 5+1;// 2

echo "5+1". 5+1;// 6

echo "5+1". 1+5;// 10</code>

Reply content:

After reading the PHP operator precedence, I can understand the examples in the manual, but this one is a bit hard to understand

<code>
echo "1+5". 1+5;// 6

echo "1+5". 5+1;// 2

echo "5+1". 5+1;// 6

echo "5+1". 1+5;// 10</code>

Refer to the instructions on php.net.

My translation (bad)

The

dot operator has the same priority as +, -, and mixed use can produce unexpected effects.

as

<code class="php">$var = 3;

echo "Result: " . $var + 3;
</code>

The above result outputs 3, instead of the expected result 6

Because the dot operator has the same precedence as +, -, all the above operations "Result: " . $var + 3; will first calculate the results of the string Result and the variable $var Got

Resuklt3

Then calculate the result of Resuklt3 and the number 3. Non-empty non-numeric strings and integers will be converted to 0 during calculation, so the result is 3

Same as echo "5+1". 1+5; The same goes for this, first calculate "5+1". 1 to get a string 5+11, (note that this is a string), in Add the number 5, the string 5+11 is converted into a number = 5, add 5 and the result is 10

The answer is very simple. Four examples illustrate one problem. The priority of string concatenator . is higher than that of operator +.
First of all, in PHP, if the variable used for addition is not of numeric type, it will be converted to numeric type first, and the string "1+15" will be converted to the number 1.
The results of these items are obvious:

<code>"1+5" . 1 + 5 = "1+15" + 5 = 1 + 5 = 6
"1+5" . 5 + 1 = "1+51" + 1 = 1 + 1 = 2
"5+1" . 5 + 1 = "5+15" + 1 = 5 + 1 = 6
"5+1" . 1 + 5 = "5+11" + 5 = 5 + 5 = 10</code>

PHP operator precedence please explain

Addition:
The string concatenator . and the arithmetic operator +- have the same priority and are at the same level. The binding direction is left, that is, calculated from left to right. refer link
So string concatenation will be performed first, and then addition operation will be performed.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn