In this tutorial, you shall learn how to create an associative array from given two indexed arrays using array_combine() function, with syntax and examples.
PHP – Create an Associative Array from Two Indexed Array
To create an associative array from given two indexed arrays, where one array is used for keys and the other array is used for values, we can use array_combine() function.
PHP array_combine() function takes keys from one input array, takes values from another input array, combines these keys and values to form a new associative array, and returns this array.
In this tutorial, we will learn how to use array_combine() function to combine array of keys and array of values to form a new array.
Syntax
The syntax of array_combine() function is
array_combine ( array $keys , array $values ) : array
where
| Parameter | Description |
|---|---|
| keys | The array of keys used to create array. |
| values | The array of values used to create array. |
Return Value
The array_combine() function returns an array formed by combining keys array and values array.
Warnings
The number of elements in keys and values arrays should match. If not, array_combine() raises a Warning.
Examples
1. Create Associative Array using Keys and Values
In this example, we will take two indexed arrays: first one is for keys, and the second one is for values. We will pass these arrays as arguments to array_combine() function and print the resulting array.
PHP Program
<?php
$keys = array(65, 66, 67);
$values = array('A', 'B', 'C');
$result = array_combine($keys, $values);
print_r($result)
?>
Output
