php变量与数组的相互转换(extract 与 compact)

作者:袖梨 2022-06-24

compact 多个变量转数组

 代码如下 复制代码

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

extract 数组转多个变量

 代码如下 复制代码

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

?>

 代码如下 复制代码

$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

相关文章

精彩推荐