Home > Article > Backend Development > How to convert key and value in php array
In PHP, you can use the array_flip() function to convert array keys and values, the syntax format is "array_flip(array);". The array_flip() function can exchange the key name of the array with its corresponding value, that is, the key name becomes the value, and the value becomes the key name.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php array key and value conversion
<?php $arr1 =array(0=>"Dog",1=>"Cat",2=>"Horse"); var_dump($arr1); $arr2=array_flip($arr1); var_dump($arr2); ?>
Rendering:
[Recommended learning: "PHP Video Tutorial"]
Introduction to related functions:
array_flip() function is used to reverse/exchange the key names in the array and the corresponding associated key values; simply put, it is to make the key names of the array and their associated key values The corresponding values are exchanged, that is, the key name becomes the value, and the value becomes the key name.
array_flip() function returns a reversed 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.
If the data type of the value in the original array is not string or integer, the function will report an error.
Grammar
array_flip(array);
For more programming-related knowledge, please visit: Programming Video! !
The above is the detailed content of How to convert key and value in php array. For more information, please follow other related articles on the PHP Chinese website!