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

青灯夜游
Release: 2023-03-13 18:10:01
Original
2336 people have browsed it

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

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

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!

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template