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

How to convert array key name to variable name in php

青灯夜游
Release: 2023-03-12 09:14:01
Original
3345 people have browsed it

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

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

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!

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