Jump to content

Arrays: concatenation operator .= vs =


StevenOliver

Recommended Posts

since the $array[] syntax always appends a new element to the array, it won't contain anything to concatenate to, so, the use of the . has no meaning and is probably producing a php undefined error. what sort of error, symptom, or problem are you having that causes you to ask this?

Link to comment
Share on other sites

It would only make sense if the "[ ]" contained a key value.

$array = [ 'First', 'Second', 'Third'];
$array[0] .= " item";                      // now you can use the concatenation operator

echo '<pre>', print_r($array, 1), '</pre>';
 /* OUTPUTS
         Array
        (
            [0] => First item
            [1] => Second
            [2] => Third
        )
*/

However,

$array[] .= " item";        // surprisingly it works!

 

Link to comment
Share on other sites

Just a reminder, in PHP 7 with strict_types, the second parameter of print_r MUST be a boolean and not an integer or it will fail with a fatal error.

Correct

<?php declare(strict_types=1); 
echo '<pre>', print_r($array, true), '</pre>';  

Fails Fatal Error

<?php declare(strict_types=1); 
echo '<pre>', print_r($array, 1), '</pre>';  

Fatal error: Uncaught TypeError: print_r() expects parameter 2 to be boolean, integer given
TypeError: print_r() expects parameter 2 to be boolean, integer given 

 

Quote

surprisingly it works!

It does "work" but it will give you an Undefined variable notice. It doesn't matter if it is an array or not.

Link to comment
Share on other sites

47 minutes ago, Barand said:

Does anyone else find it ironic that you can't


declare(strict_types=true);

 

According to Andrea (the original author of the scalar type hints RFC where strict_types came from),

Quote

I originally had it be a boolean, but considering how often this would be used, I changed it to 1 for terseness. Using 1 is common for INI settings, so I don’t think it’d be that confusing,

Shrug.

Link to comment
Share on other sites

18 minutes ago, Barand said:

... or how little?

Either you use it everywhere or you don't use it at all. I'm in the latter camp: I like the automatic conversions, and I'm already aware of and careful with value types.

I would probably opt-in if I could do it globally, but there were good reasons not to support that and to only make it per-file.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.