Search code examples
phparraysassociative-arraymerging-data

Combine two flat arrays into key-value pairs of a new associative array


$fruit = array(0 => "Lemon", 1 => "Apple");
$order = array(0 => "no1", 1 => "no2");
$new_array = array();
foreach ($order as $index) {
    $new_array[$index] = $fruit[$index];
}
print_r($new_array);

It shows:

Notice: Undefined index: no1 in C:\xampp\htdocs\jobs.php on line 6
Notice: Undefined index: no2 in C:\xampp\htdocs\jobs.php on line 6

What should I do?


Solution

  • You should use array_combine() function available in PHP (see PHP Docs) :

    "array_combine — Creates an array by using one array for keys and another for its values"

    $fruit = array(0 => "Lemon", 1 => "Apple");
    $order = array(0 => "no1", 1 => "no2");
    $new_array = array_combine($order, $fruit);
    print_r($new_array);
    

    // Output : Array ( [no1] => Lemon [no2] => Apple )

    Working example: https://3v4l.org/rW71r