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

compact 多个变量转数组,代码如下:

  1. <?php
  2. //多个变量转数组
  3. $name='phpff';
  4. $email='phpff@phpff.com';
  5. $info=compact('name','email');//传递变量名
  6. print_r($info);
  7. /*
  8. Array
  9. (
  10. [name] => phpff
  11. [email] => phpff@phpff.com
  12. )
  13. */
  14. ?>

extract 数组转多个变量,代码如下:

  1. <?php
  2. //数组转多个变量
  3. $capitalcities['England'] = 'London';
  4. $capitalcities['Scotland'] = 'Edinburgh';
  5. $capitalcities['Wales'] = 'Cardiff';
  6. extract($capitalcities);//转变成三个变量 England,Scotland,Wales
  7. print $Wales;//Cardiff
  8. ?>

实例代码如下:

  1. <?php
  2. $my_array = array("a" => "Cat","b" => "Dog", "c" => "Horse");
  3. extract($my_array);
  4. echo "$a = $a; $b = $b; $c = $c";
  5. ?>
  6. //结果
  7. //$a = Cat; $b = Dog; $c = Horse