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

2

Why this:

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 this particular case , with and without the parentheses, returns different values?

    
asked by anonymous 24.07.2017 / 15:44

3 answers

4

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

  

You were born in 1997

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

  

You were born in 2017

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

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

When subtracting with 20 will give -20

It is therefore important to specify the order of operations.

    
24.07.2017 / 15:54
3

Relatives as well as mathematics give priority to some operation, so the first echo works as expected ie it does the account and then writes the result.

P1, P2 = Order of priorities

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

While the second works differently, the php interpreter tries to solve everything at once in the order it thinks correct, in that the string "Você nasceu em ". is concatenated with the result of date() and tries to subtract with less - 20, as the generated string is not a number, it is automatically converted to zero, so the result is -20, see that Você nasceu em does not print.

echo "Você nasceu em ". date('Y') - 20;
        P1---^---------------^
                            p2---^    
    
24.07.2017 / 15:56
3

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

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

echo "Você nasceu em 2017" - 20;

So it's important to use parentheses. For in such cases, the expression is first processed inside the parentheses and then concatenated.

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

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

See a test at IDEONE

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

  

A non-numeric value encountered

    
24.07.2017 / 15:58