yaylitzis
yaylitzis

Reputation: 5544

Concatenation-assignment in PHP

I am learning PHP and I just read about Assignment Operators and I saw this $a .= 5 which means $a equals $a concatenated with 5. To test this I coded a simple script

    <?php
        $a = 12345;
        $a .=6;

        $b = 12345;
        $b .=006;

        $c = 12345;
        $c .=678;
        echo " a=$a and b=$b c=$c" ;

    ?>

the output was a=123456 and b=123456 c=12345678.My question is why the b isn't equal with 12345006? Is it because treats 6 == 006?

Upvotes: 0

Views: 277

Answers (3)

dev4092
dev4092

Reputation: 2891

Just try b as a string:

$b.= '006';

Then you will get output 12345006.

Upvotes: 0

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76415

Because numbers with leading zeroes are treated as octals. if the concatenation would've included the leading zeroes, then 006 would've been interpretted as a string, which makes no sense, because it hasn't got quotes around it.
If you want 006 to be treated as a string, write it as one: '006'. Leave it as is, and it'll be interpreted as an octal:

$b = $a = 123;
$a .= 8;
$b .= 010;//octal
echo $a, ' === ', $b, '!';//echoes 1238 === 1238!

Just as an asside: yes, those are comma's/. echo is a language construct to which you can push multiple values, separated by comma's. The upshot of using comma's is that the values aren't concatenated into a single string before being pushed to the output stream.
This means that it is (marginally faster). The downsides: there aren't any AFAIK.

In case you're interested in the internals of PHP, I've explain this a bit more detailed here...

Upvotes: 3

Tam&#225;s Zahola
Tam&#225;s Zahola

Reputation: 9311

Because 006 is treated as the octal number 6, which is the converted to the string "6", and concatenated to "12345" (which is the number 12345 converted to a string). Use $b .= "006", and the result will be 12345006.

Upvotes: 5

Related Questions