Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP commands the same when adding to an array?

Tags:

arrays

php

Just curious if doing this

$this->item['foo'] = $this->action(3);
$this->item['bar'] = $this->action(1);
$this->item['baz'] = $this->action(1);

is the same as doing

$this->item = ($this->item +
[
    'foo'  => $this->action(3),
    'bar'  => $this->action(1),
    'baz'  => $this->action(1),
]);

if you could explain why/why not I'd be appreciative

like image 241
ehime Avatar asked Feb 15 '23 01:02

ehime


1 Answers

They're not equivalent if $this->item already has any of the keys you're specifying. From the documentation:

for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.

You can resolve this by switching the order of arguments:

$this->item = (
    [
    'foo'  => $this->action(3),
    'bar'  => $this->action(1),
    'baz'  => $this->action(1),
    ] + $this->item);
like image 54
Barmar Avatar answered Feb 22 '23 23:02

Barmar