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?
Prepend and Append Strings in PHPYou can use the concatenation operator . if you want to join strings and assign the result to a third variable or output it. This is useful for both appending and prepending strings depending on their position. You can use the concatenating assignment operator .
Due to this, mixing the StringBuilder and + method of concatenation is considered bad practice. Additionally, String concatenation using the + operator within a loop should be avoided. Since the String object is immutable, each call for concatenation will result in a new String object being created.
If you want to concatenate a string and a number, such as an integer int or a floating point float , convert the number to a string with str() and then use the + operator or += operator.
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
That's strange...
But
<?php
echo '11hello ' . (1 + 2) . '34';
?>
or
<?php
echo '11hello ', 1 + 2, '34';
?>
fixes the issue.
UPDATE v1:
I finally managed to get the proper answer:
'hello'
= 0
(contains no leading digits, so PHP assumes it is zero).
So 'hello' . 1 + 2
simplifies to 'hello1' + 2
is 2
. Because there aren't any leading digits in 'hello1'
it is zero too.
'11hello '
= 11
(contains leading digits, so PHP assumes it is eleven).
So '11hello ' . 1 + 2
simplifies to '11hello 1' + 2
as 11 + 2
is 13
.
UPDATE v2:
From Strings:
The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With