This article demonstrates converting a regular array to an associative array in PHP.

1. Using array_combine() function

The array_combine() function creates an array by using the array specified as the first argument for keys and the array specified as the second argument for its values.

Download  Run Code

 
Note that in PHP 8 and above, a “ValueError” is thrown if argument #1 ($keys) and argument #2 ($values) do not have the same number of elements. In older PHP versions, false is returned instead. Here’s a slightly modified version that can easily handle arrays of different sizes. It works by trimming the shorter array before invoking the array_combine() function.

Download  Run Code

 
If the first array has any duplicates, the associated value of the latest key is used, and all others will be ignored. For example,

Download  Run Code

2. Using array_fill_keys() function

The array_fill_keys() function creates an array using the values of the array specified in the first parameter for its keys, and the value specified in the second parameter for its values. The following example creates an associative array for storing the letter frequency.

Download  Run Code

3. Using foreach loop

Another option is to loop through the regular array and insert each value into the associative array manually. For example, the following snippet creates an associative array of points table and initializes it using a foreach loop.

Download  Run Code

4. Using array_flip() function

Finally, you can use the array_flip() function, which swaps all keys in an array with their corresponding values. The following is a simple example demonstrating the usage of the array_flip() function on a numeric array. It creates a new array in reverse order, i.e. keys from the original array become values, and the values become keys.

Download  Run Code

 
Note that if a value has several occurrences, the later key of two duplicates is preserved and the earlier one is lost:

Download  Run Code

That’s all about converting a regular array to an associative array in PHP.