php变量与数组的相互转换(extract)与(compact)
compact 多个变量转数组,代码如下:
- <?php
- //多个变量转数组
- $name='phpff';
- $email='phpff@phpff.com';
- $info=compact('name','email');//传递变量名
- print_r($info);
- /*
- Array
- (
- [name] => phpff
- [email] => phpff@phpff.com
- )
- */
- ?>
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