Thursday, 30 August 2018

PHP: merge two tables, but keep the keys of the first one

This question already has an answer here:

  • How to merge two arrays by taking over only values from the second array that has the same keys as the first one? 2 answers
I've got this method which merges two arrays, like this :
<?php
$array1 = [
    'huey' => 0,
    'dewey' => 1,
    'louie' => 2
];

$array2 = [
    'dewey' => 3,
    'beagle boys' => '  167-671'
];

$array3 = array_merge($array1, $array2);

var_dump($array3);

The problem is, even if the key "dewey" is updated, I don't want my array to have the "beagle boys" key. How can I update my code to output only keys which are on the first array ?

$array3 = array_merge(
    $array1,
    array_intersect_key($array2, $array1)
);

0 comments:

Post a Comment