+4 votes
in Programming Languages by (6.2k 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

0 votes
by (25.6k points)

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
)

...