PHP变量与关联数组的相互转换 (extract 与 compact),工作中很实用!

compact 多个变量转数组

 代码如下  

<?php
    //多个变量转数组
    $name='phpff';
    $email='[email protected]';
    $info=compact('name','email');//传递变量名
    print_r($info);
    /*
    Array
    (
        [name] => phpff
        [email] => [email protected]
    )
    */
?>

extract 数组转多个变量

 代码如下  

<?php
//数组转多个变量
    $capitalcities['England'] = 'London';
    $capitalcities['Scotland'] = 'Edinburgh';
    $capitalcities['Wales'] = 'Cardiff';
    extract($capitalcities);//转变成三个变量 England,Scotland,Wales
    print $Wales;//Cardiff

?>

 代码如下  

<?php
$my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
extract($my_array);
echo "$a = $a; $b = $b; $c = $c";
?>

结果

$a = Cat; $b = Dog; $c = Horse


发布了14 篇原创文章 · 获赞 21 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/wanghongbiao1993/article/details/53595935
今日推荐