Home>Article>Backend Development> How to convert index array into associative array in php
In PHP, you can use the array_combine() function to convert the index array into an associative array. The syntax is "array_combine (array containing key names, index array)"; among them, the key name array and the index array The number of elements must be consistent, so that the key name can correspond to the element value in the index array one-to-one.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In php, you can use array_combine () function to convert the index array into an associative array.
Example:
There is such an index array:
array (size=4) 0 => string 'red' (length=3) 1 => string 'green' (length=5) 2 => string 'blue' (length=4) 3 => string 'yellow' (length=6)
Want to convert it into an associative array:
array (size=4) 'a' => string 'red' (length=3) 'b' => string 'green' (length=5) 'c' => string 'blue' (length=4) 'd' => string 'yellow' (length=6)
We can use array_combine () function and an array containing "a", "b", "c", "d" elements:
array("a","b","c","d");
Implementation code:
Description:
array_combine($keys,$values)
The function creates a new array by merging two arrays, whereThe elements in the $keys
array are used as the keys of the new array, and the elements in the$values
array are used as the key values of the new array.
But it should be noted that when using the array_combine() function to create an array, the number of elements in the $keys array and the $values array must be consistent, so that the key names and key values can correspond one to one, otherwise An error will be reported and FALSE will be returned.
And the$keys
array cannot be a multi-dimensional array, otherwise an error will be reported; but the$values
array can be a multi-dimensional array.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert index array into associative array in php. For more information, please follow other related articles on the PHP Chinese website!