Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two arrays in PHP

I am trying to create a new array from two current arrays. Tried array_merge, but it will not give me what I want. $array1 is a list of keys that I pass to a function. $array2 holds the results from that function, but doesn't contain any non-available resuls for keys. So, I want to make sure that all requested keys comes out with 'null':ed values, as according to the shown $result array.

It goes a little something like this:

$array1 = array('item1', 'item2', 'item3', 'item4');

$array2 = array(
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => 'value3'
);

Here's the result I want:

$result = array(
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => 'value3',
    'item4' => ''  
);

It can be done this way, but I don't think that it's a good solution - I really don't like to take the easy way out and suppress PHP errors by adding @:s in the code. This sample would obviously throw errors since 'item4' is not in $array2, based on the example.

foreach ($keys as $k => $v){
    @$array[$v] = $items[$v]; 
}

So, what's the fastest (performance-wise) way to accomplish the same result?

like image 844
Industrial Avatar asked Jun 24 '26 17:06

Industrial


2 Answers

array_fill_keys will build you a nice array you can use in array_merge:

array_merge(array_fill_keys($array1, ''), $array2);

Or, instead of array_merge, you can use the + op which performs a union:

$array2 + array_fill_keys($array1, '');

This one works with numerical keys or mixed numerical/strings :)

like image 68
Chris Avatar answered Jun 27 '26 23:06

Chris


Instead of throwing errors check that the key exits using array_key_exists

<?php
 foreach($array1 as $key) {
    if (array_key_exists($key, $array2)) {
        $result[$key] = $array2[$key];
    } else {
        $result[$key] = null;
    }
 }
like image 30
Alistair Avatar answered Jun 28 '26 01:06

Alistair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!