$v){$arr2[$v]=$k;}", use the value of the original array as empty The key of the array, the key of the original array can be used as the value of the empty array. 2. Use the array_flip() function, which can exchange keys and values in the array, with the syntax "array_flip($array)"."/> $v){$arr2[$v]=$k;}", use the value of the original array as empty The key of the array, the key of the original array can be used as the value of the empty array. 2. Use the array_flip() function, which can exchange keys and values in the array, with the syntax "array_flip($array)".">
Home >Backend Development >PHP Problem >How to convert the position between key and value in php array
Two conversion methods: 1. Use foreach loop and an empty array, the syntax "foreach($arr1 as $k=>$v){$arr2[$v]=$k;}", Just use the value of the original array as the key of the empty array, and the key of the original array as the value of the empty array. 2. Use the array_flip() function, which can exchange keys and values in the array, with the syntax "array_flip($array)".
The operating environment of this tutorial: windows7 system, PHP8.1 version, DELL G3 computer
php will Key and value conversion position
Method 1: Use foreach loop and an empty array
<?php $arr1=array("aaa"=>11,"bbb"=>22,"ccc"=>33); $arr2=array(); foreach($arr1 as $k=>$v){ $arr2[$v]=$k; } var_dump($arr2); ?>
Output result:
Method 2: Use array_flip() function
array_flip() function can exchange the keys and values in the array
<?php $arr1=array("aaa"=>11,"bbb"=>22,"ccc"=>33); $arr2=array_flip($arr1); var_dump($arr2); ?>
Output result:
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert the position between key and value in php array. For more information, please follow other related articles on the PHP Chinese website!