+4 votes
in Programming Languages by (56.8k points)

I want to create an associative array using the elements of one array as keys and elements of another array as values. How can I create the associative array?

E.g.

From

$product = array("aa", "bb", "cc", "dd");

$price = array("11", "22", "33", "44");

To

Array

(

    [aa] => 11

    [bb] => 22

    [cc] => 33

    [dd] => 44

)

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

The array_combine() function can be used to create an associative array using the elements from one array as keys and elements from another array as values:

Here is an example:

<?php

$product = array("aa", "bb", "cc", "dd");
$price = array("11", "22", "33", "44");
$prod_price = array_combine($product, $price);
print_r($prod_price);

?>

The output of the above code:

Array
(
    [aa] => 11
    [bb] => 22
    [cc] => 33
    [dd] => 44
)


...