Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string number concatenation messed up

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?

like image 970
JustinHo Avatar asked Apr 30 '13 07:04

JustinHo


People also ask

Can we concatenate string and integer in PHP?

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 .

Is string concatenation bad?

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.

Can you concatenate numbers and strings?

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.

What is wrong with string concatenation in loop?

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.


1 Answers

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.

like image 68
BlitZ Avatar answered Oct 19 '22 20:10

BlitZ