Today came across code that used the + sign to merge two associative php arrays. At first I thought it was broken but turns out you can indeed merge two arrays with the + sign.
$album = array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
);
$album_meta_data = array(
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
);$output = $album + $album_meta_data;
——–OUTPUT——–
array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
)
Another way to use it would be to add the album meta data directly to the album array.
$album = array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
);
$album_meta_data = array(
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
);$album += $album_meta_data;
——–OUTPUT——–
array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
)
If the key exists in both arrays then the first if used and the second is discarded, same as with array_merge.
$album = array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
);
$album_meta_data = array(
‘title’ => ‘Coldplay’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
);$album += $album_meta_data;
——–OUTPUT——–
array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
)
the reverse
$album = array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Radiohead’,
);
$album_meta_data = array(
‘title’ => ‘Coldplay’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
);$album_meta_data += $album;
——–OUTPUT——–
array(
‘title’ => ‘King of Limbs’,
‘band’ => ‘Coldplay’,
‘upc’ => ’486898161589′,
‘price’ = ’11.98′
)