Santosh Bohara Santosh Bohara - 2 months ago 6
PHP Question

merge two array php and replace values

I have 2 array as below :

Array 1
(
[0] => c1
[1] => c2
[2] => c3
)

Array 2
(
[0] => Son
[1] => Daughter
[2] => Son
)


Output required :

Array (
c1 => Son
c2 => Daughter
c3 => Son
)


Can anyone please guide to generate this output ? Thank you.

Answer

Try this:

$array_result = array();

foreach($array1 as $key => $val) {
    $array_result[$val]=$array2[$key];
}

So you are building a new array (array_result), while using the values from array1 as the keys and the values from array2 as the values of the new array.

As @max-p wrote, array_combine() does the same thing as the above and it's one line, so go with that, but hopefully the example illustrates what's going on.