Combining two arrays in PHP

I am trying to create a new array from two current arrays. Tried array_merge but it wont give me what i want. $array1is a list of keys that I pass to the function. $array2contains the results of this function, but does not contain any keys available for keys. Therefore, I want to make sure that all requested keys are returned with zero values: ed, as shown in the array shown $result.

This is a bit like this:

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

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

Here is the result I want:

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

You can do it this way, but I don’t think this is a good solution - I really don’t like to take a simple exit and suppress PHP errors by adding @: s to the code. This pattern will obviously throw errors because 'item4'it is not in $array2, based on this example.

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

, ( ) ?

+3
6

array_fill_keys , array_merge:

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

array_merge + op, :

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

/:)

+5

, , , array_key_exists

<?php
 foreach($array1 as $key) {
    if (array_key_exists($key, $array2)) {
        $result[$key] = $array2[$key];
    } else {
        $result[$key] = null;
    }
 }
+1
0

array_merge array_fill_keys:

$result = array_merge(
    array_array_fill_keys($array1,''),
    $array2
);

, array_merge , , , $array1 . , , :

$array1 = array(1,2,3);
$array2 = array("hi"=>"world",2=>"test","other"=>"empty");

:

array(6) {
  [0]=>
  string(0) ""
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  ["hi"]=>
  string(5) "world"
  [3]=>
  string(4) "test"
  ["other"]=>
  string(5) "empty"

}

, - ,

0

, , array_fill_keys , , .

$array1 = (array)$array2 + (array)$array1;
0

array_combine? : PHP

It seems that you are doing exactly what you want with one caveat: if two arrays do not have the same size, it does nothing. If it is guaranteed that your key array will always be longer than your array of values, you can simply put an array of values ​​with zero values ​​until both arrays are of equal size before calling array_combine.

-1
source

Source: https://habr.com/ru/post/1746709/


All Articles