I got some php code here:
<?php
echo 'hello ' . 1 + 2 . '34';
?>
which outputs 234,
but when I add a number 11 before "hello":
<?php
echo '11hello ' . 1 + 2 . '34';
?>
It outputs 1334 rather than 245(which I expected it to), why is that?
you have to use
()
in mathematical operationThat's strange...
But
OR
fixing issue.
UPDv1:
Finally managed to get proper answer:
'hello'
=0
(contains no leading digits, so PHP assumes it is zero).So
'hello' . 1 + 2
simplifies to'hello1' + 2
is2
, because no leading digits in'hello1'
is zero too.'11hello '
=11
(contains leading digits, so PHP assumes it is eleven).So
'11hello ' . 1 + 2
simplifies to'11hello 1' + 2
as11 + 2
is13
.UPDv2:
http://www.php.net/manual/en/language.types.string.php
The dot operator has the same precedence as + and -, which can yield unexpected results.
That technically answers your question... if you want numbers to be treated as numbers during concatination just wrap them in parenthesis.
If you hate putting operators in between assign them to vaiable
You should check PHP type conversion table to get better idea what's happen behind the scenes: http://php.net/manual/en/types.comparisons.php