phparraysmappingassociative-arrayfallbackvalue

Map values from one flat array to another flat array by key and fallback to null where there is no corresponding value


Having Two arrays need to Merge two arrays with matching their keys and rest should be empty. I have tried array_merge(), array_diff(), array_fill() but nothing helped.

Array one

Array
    (
        [5] => PHM
        [4] => ODM
        [3] => N
        [6] => M9
        [10] => RDM9
    )

array 2

Array
  (
    [0] => 01
    [1] => 02
    [2] => 03
    [3] => 04
    [4] => 05
    [5] => 06
    [6] => 07
    [7] => 08
    [8] => 09
    [9] => 10
    [10] => 11
    [11] => 12
    [12] => 13
   )

Final Output

Array
  (
    [0] => null 
    [1] => null 
    [2] => null 
    [3] => N
    [4] => ODM
    [5] => PHM
    [6] => M9
    [7] => null 
    [8] => null 
    [9] => null 
    [10] => RDM9
    [11] =>  null   
    [12] => null 
   )

Solution

  • Make array with all nulls from the 2nd array and replace by values from the 1st array

    $arr2 = array_fill_keys(array_flip($arr2), null);
    $new = array_replace($arr2, $arr1);
    print_r($new);