$value){$$key=$value;}"; 2. Use extract() Function, the syntax is "extract($arr);"."/> $value){$$key=$value;}"; 2. Use extract() Function, the syntax is "extract($arr);".">

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

How to convert array key name to variable name in php

青灯夜游
青灯夜游Original
2021-09-01 10:18:443290browse

php method to convert array key names into variable names: 1. Use foreach loop, syntax "foreach($arr as $key=>$value){$$key=$value;}"; 2. Use the extract() function with the syntax "extract($arr);".

How to convert array key name to variable name in php

The operating environment of this article: Windows7 system, PHP7.1 version, Dell G3 computer

php The key name is the variable name, and the key value is the variable name

Method 1: Use a foreach loop to achieve

<?php
$arr=array(&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>5,&#39;e&#39;=>6); 

foreach($arr as $key=>$value){ 
 $$key=$value; 
}   
echo $a."<br>"; 
echo $b;
?>

output Result:

How to convert array key name to variable name in php

Method 2: Using the extract() function

extract() function from the array Import variables into the current symbol table. This function uses the array key name as the variable name and the array key value as the variable value. For each element in the array, a corresponding variable will be created in the current symbol table. This function returns the number of variables successfully set.

<?php
$arr=array(&#39;a&#39;=>1,&#39;b&#39;=>2,&#39;c&#39;=>3,&#39;d&#39;=>5,&#39;e&#39;=>6); 

extract($arr); 

echo $a."<br>"; 
echo $b."<br>"; 
echo $c."<br>"; 
echo $d; 
?>

Output result:

How to convert array key name to variable name in php

Recommended: "PHP Video Tutorial"

The above is the detailed content of How to convert array key name to variable name 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