Conversion between PHP variables and arrays (extract and compact)_PHP tutorial

WBOY
Release: 2016-07-13 10:49:55
Original
1252 people have browsed it

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
$a = Cat; $b = Dog; $c = Horse
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...
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!