0

To keep it short, why does

<?php
$var =  'Calc: ' . 5 - 5 . '!';
echo $var;
?>

output:

-5!

Instead of, let's say:

Calc: 0 . '!'


Or another variation of this problem:

<?php
echo "time is" . time()-2;
?>

Prints:

-2

Notice the corruption, the first "string" with the first int is chopped off! Though, < $var = 'Calc: ' . (5 - 5) . '!'; > (does work ok), I'm trying to understand what the key concept behind this behavior is.

1 Answers1

-2

Good old math comes and saves the day.
Adding () means it will be calculated first and give you a correct string.

$var =  'Calc: ' . (5 - 5) . '!';
echo $var; //Calc: 0!

https://3v4l.org/p8OYf

Andreas
  • 23,610
  • 6
  • 30
  • 62
  • 1
    The question is not how to solve it, he States at the end that he knows that using parentheses works ok. The question is why 5 - 5 gets inserted as -5 like the 5 was not there –  Sep 29 '18 at 18:54
  • @Dknacht and that is what my answer explains. The parentheses makes the code first evaluate the math. If it's not evaluated first then you will have a string that you try to do math on. – Andreas Sep 29 '18 at 18:58