How to convert array value to key in php

青灯夜游
Release: 2023-03-16 06:14:02
Original
4269 people have browsed it

3 methods: 1. Use the "array_flip($arr)" statement; 2. Use the "array_combine($arr,array_keys($arr))" statement; 3. Use "foreach($arr1 as $ k=>$v){$arr2[$v]=$k;}" statement.

How to convert array value to key in php

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

php converts the array value into key, that is Convert the keys and values ​​in the array to each other. Three methods are introduced below:

Method 1: Use array_flip() function

array_flip() function can exchange keys and values ​​​​in the array

<?php
$arr1=array("aaa"=>11,"bbb"=>22,"ccc"=>33);
var_dump($arr1);
$arr2=array_flip($arr1);
var_dump($arr2);
?>
Copy after login

How to convert array value to key in php

Method 2: Use array_keys() array_combine() function

Implementation idea:

  • Use array_keys () Obtain the key name in the array and return the key name array

  • Use array_combine() to use the original array as the key name and the key name array as the key value to merge into a new array

<?php
$arr=array("Peter"=>11,"Ben"=>22,"Joe"=>33);
var_dump($arr);
$keys=array_keys($arr);
var_dump(array_combine($arr,$keys));
?>
Copy after login

How to convert array value to key in php

Method 3: Using a 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

How to convert array value to key in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert array value to key in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!