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?
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?
I think it is a good idea to have a different operator, because dot and plus do completely different things.
What does "a string" + "another string";
actually mean, from a non specific language point of view?
Does it mean
You would assume it is the second, but a plus sign is used for numerical addition in all cases except Strings. Why?
Also, from a loosely typed point of view (which PHP is), a php script
$myvar = 1;
$myvar2 = 2;
// would we expect a concatenation or addition?
$concat = $myvar + $myvar2;
The dot notation therefore specifies that it is clearly used for concatenation.
It is not that it is confusing, it is that it is not intuitive because all the other languages do it in a different way. And, is this a good reason to follow the trend? Doing things the way they are always done, is not always the right way.
The .
operator is the concatenation operator. Your first example only works because the echo 'function' (technically it's a language construct, but lets not split hairs) accepts more than one parameter, and will print each one.
So your first example is calling echo with more than one parameter, and they are all being printed, vs. the second example where all the strings are being concatentated and that one big string is being printed.
The cast will occur before the division.
In your examples, it doesn't matter which one you do as if one operand is a double, the runtime will cast/convert the other to a double as well.
This looks like a micro-optimization - not something worth worrying about or dealing with unless measurements show it is indeed a bottleneck.
That'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