$v)" {$arr2[$v]=$k;}" statement."/> $v)" {$arr2[$v]=$k;}" statement.">

Home  >  Article  >  Backend Development  >  How to convert array value to key in php

How to convert array value to key in php

青灯夜游
青灯夜游Original
2022-05-09 19:31:134088browse

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

11,"bbb"=>22,"ccc"=>33);
var_dump($arr1);
$arr2=array_flip($arr1);
var_dump($arr2);
?>

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

11,"Ben"=>22,"Joe"=>33);
var_dump($arr);
$keys=array_keys($arr);
var_dump(array_combine($arr,$keys));
?>

How to convert array value to key in php

Method 3: Using a foreach loop and an empty array

11,"bbb"=>22,"ccc"=>33);
$arr2=array();
foreach($arr1 as $k=>$v){
    $arr2[$v]=$k;
}
var_dump($arr2);
?>

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!

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