Why does the use of parentheses affect a mathematical expression combined with a concatenation?

Asked

Viewed 58 times

2

Why:

echo "Você nasceu em ". (date('Y') - 20); //Retorna correto, no caso, se a idade for 20, retorna 1997
echo "Você nasceu em ". date('Y') - 20; // Retorna -20

Why in that particular case, with and without parentheses, returns different values?

3 answers

4


With parentheses the calculation is made first date('Y') - 20 that of the 1997 and then concatenated with the string that gives the text:

You were born in 1997

Without parentheses the concatenation with the year is first made, giving:

You were born in 2017

Then converted into an integer in order to subtract 20. Converting "Você nasceu em 2017" in full gives 0 for the first letter is a "V" and not numbers:

var_dump((int)("Você nasceu em ". date('Y'))); //escreve int(0)

When subtracts with 20 will give -20

Therefore it is important to specify the order of operations.

  • I got it, in case he picks up the string too. I thought he only solved the operation I did. But then I got it, thank you Isac! And thanks to the others too!

3

Parentheses as in mathematics give priority to some operation, so the first echo works as expected or is does the account and then writes the result.

P1, P2 = Order of priorities

echo "Você nasceu em ". (date('Y') - 20);
                             P1----^
P2-----------^

The second one works differently, the php interpreter tries to solve everything at once in the order he thinks is correct, this one takes the string "Você nasceu em ". concatenates with the result of date() and tries to replace with minus -20, as the generated string is not an automatic number is converted to zero, so the result is -20 see that the snippet Você nasceu em is not printed.

echo "Você nasceu em ". date('Y') - 20;
        P1---^---------------^
                            p2---^    

3

In the expression echo "Você nasceu em ". date('Y') - 20, you are subtracting the string concatenation with the date.

For you to understand better, it would be the same thing for you to do it:

echo "Você nasceu em 2017" - 20;

Therefore it is important to use the parentheses. For in such cases, the expression is first processed within the parentheses and then concatenated.

Tip: In cases like this, I usually use the function sprintf to better format the string:

echo sprintf("Você nasceu em %d", date('Y') - 20);

See a test on IDEONE

Note: Depending on the version of PHP you are using (I believe from version 7 onwards), you may get an error if you do an operation like this mentioned in the question:

A non-numeric value encountered

Browser other questions tagged

You are not signed in. Login or sign up in order to post.