How to convert index array into associative array in php

青灯夜游
Release: 2023-03-15 07:00:01
Original
2507 people have browsed it

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)
Copy after login

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)
Copy after login

We can use array_combine () function and an array containing "a", "b", "c", "d" elements:

array("a","b","c","d");
Copy after login

Implementation code:

Copy after login

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, where The 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!