Home>Article>Backend Development> How to convert index array into associative array in php

How to convert index array into associative array in php

青灯夜游
青灯夜游 Original
2022-01-27 15:48:18 2472browse

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.

How to convert index array into associative array in php

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:

       

How to convert index array into associative array in php

Description:

array_combine($keys,$values)The function creates a new array by merging two arrays, whereThe elements in the $keysarray are used as the keys of the new array, and the elements in the$valuesarray 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$keysarray cannot be a multi-dimensional array, otherwise an error will be reported; but the$valuesarray 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn