Home  >  Article  >  Backend Development  >  How to convert array key values ​​in php

How to convert array key values ​​in php

青灯夜游
青灯夜游Original
2021-06-09 18:25:342973browse

In PHP, you can use the array_flip() function to convert array key values, the syntax is "array_flip(array)". The array_flip() function returns a swapped array. If the same value appears multiple times, the last key name will be used as its value, and all other key names will be lost.

How to convert array key values ​​in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

In php, you can use array_flip () function to convert array key values.

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
print_r(array_flip($trans));
$trans = array(&#39;a&#39;, &#39;b&#39;, &#39;1&#39;, 2, 3);
print_r(array_flip($trans));
?>

Output:

Array
(
    [1] => b
    [2] => c
)
Array
(
    [a] => 0
    [b] => 1
    [1] => 2
    [2] => 3
    [3] => 4
)

Description:

array_flip() function is used to reverse/exchange all the elements in the array Key names and their associated key values. The syntax is as follows:

array array_flip ( array )

trans The value in the array needs to be a legal key name, for example, it needs to be integer or string. A warning will be emitted if the value is of the wrong type, and the offending key-value pair will not be reversed.

If the same value appears multiple times, the last key name will be used as its value, and all others are lost.

Return value: The exchanged array is returned if the execution is successful, and NULL is returned if it fails.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert array key values ​​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