In PHP, we can use the extract or compact function to convert arrays and variables. Let me share two examples with you using these two functions.
compact multiple variables to array
The code is as follows
代码如下 |
复制代码 |
//多个变量转数组
$name='phpff';
$email='phpff@phpff.com';
$info=compact('name','email');//传递变量名
print_r($info);
/*
Array
(
[name] => phpff
[email] => phpff@phpff.com
)
*/
?>
|
|
Copy code
|
代码如下 |
复制代码 |
//数组转多个变量
$capitalcities['England'] = 'London';
$capitalcities['Scotland'] = 'Edinburgh';
$capitalcities['Wales'] = 'Cardiff';
extract($capitalcities);//转变成三个变量 England,Scotland,Wales
print $Wales;//Cardiff
?>
|
//Convert multiple variables to array
$name='phpff';
$email='phpff@phpff.com';
$info=compact('name','email');//Pass variable name
Print_r($info);
/*
Array
(
[name] => phpff
[email] => phpff@phpff.com
)
*/
?>
代码如下 |
复制代码 |
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "$a = $a; $b = $b; $c = $c";
?>
|
extract array to multiple variables
The code is as follows
|
Copy code |
|
//Convert array to multiple variables
$capitalcities['England'] = 'London';
$capitalcities['Scotland'] = 'Edinburgh';
$capitalcities['Wales'] = 'Cardiff';
Extract($capitalcities);//Convert into three variables England, Scotland, Wales
Print $Wales;//Cardiff
?>
Example
The code is as follows
|
Copy code
|
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "$a = $a; $b = $b; $c = $c";
?>
Results
http://www.bkjia.com/PHPjc/632672.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632672.htmlTechArticleIn php, we can use the extract or compact function to convert arrays and variables into each other. Let me use it for everyone. Let’s share two examples of these two functions. compact multiple variables to array...
|
|