$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

How to convert the position between key and value in php array

青灯夜游
青灯夜游Original
2021-11-05 18:25:562330browse

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)".

How to convert the position between key and value in php 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:

How to convert the position between key and value in php array

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:

How to convert the position between key and value in php array

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!

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