Search code examples
phparraysmappingassociative-arraymerging-data

Populate an associative array from an array of dates and another array with values for not all dates


Here's what I'm doing:

$dateRange = array('2010-01-01', '2010-01-02', '2010-01-03', ...);
$data = array('2010-01-01' => 5, '2010-01-03' => 7);

foreach ($dateRange as $date) {
    $values[$date] = $data[$date];
}

$values results in:

array (
    '2010-01-01' => 5
    '2010-01-02' => null
    '2010-01-03' => 7
    ...
)

Seems fairly efficient, but I wonder if there's a simple PHP function that'll handle this.


Solution

  • $values = array_merge(array_fill_keys($dateRange, null), $data);
    

    Whether that's really any more efficient can only be found out through testing, but I'd say it's more concise, easy to understand, and it doesn't throw errors for non-existent keys in $data. :)