phparraysassociative-array

Use an array of keys and an array of values to form an associative array


I want to merge two arrays where first array will be keys and second array will be values in result array.

$array1 = array('k1', 'k2');
$array2 = array('v1', 'v2'); 

output should be:

array(
    'k1' => 'v1',
    'k2' => 'v2',
)

Solution

  • You can use the array_combine function. This function uses one array for keys, and one array for values.

    You can use it as:

    array_combine ( $keys, $values );
    

    In your case it would be:

    $array1 =array('k1','k2');
    $array2 =array('v1','v2'); 
    
    $combined_array = array_combine ( $array1, $array2 );