in php, what is the purpose of using concatenation operator (.) for adding values to an array?

Shaon Hasan :

I am relatively new to php and was following a tutorial where there was a code to add values to array like this:

$errors = array();
$errors[] .= 'You must enter a value';

So I am confused about the above code.

I know that i can declare and add values to array like below.

$myarr = array();
$myarr[]= "aa";
$myarr[]= "bb";

print_r($myarr);

Also, I can append strings by using string concatenation operator (.) like below:

$str = "val1"."val2";

But what's the point of putting concatenation operator (.) before adding a value to an array?

Nick :

In this particular case there is no point in using the concatenation operator. The left hand side of the expression, $errors[] creates a new, empty, element in the $errors array, so concatenating something to it has the same effect as assigning to it. Indeed if you try the following code with and without the concatenation operator, you'll see the results are the same:

$errors = array();
$errors[] .= 'You must enter a value';
print_r($errors);

$errors = array();
$errors[] = 'You must enter a value';
print_r($errors);

Output:

Array
(
    [0] => You must enter a value
)
Array
(
    [0] => You must enter a value
)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9693&siteId=1