「5.6配列と変数の変換」からのメモ。
- extract()を使って連想配列をキーを変数名として展開する
<?php $hoge = array("first" => "a" , "second" => "b" , "third" => "c"); extract($hoge , EXTR_PREFIX_ALL , "hoge"); echo "\$hoge_first = $hoge_first\n"; echo "\$hoge_second = $hoge_second\n"; echo "\$hoge_third = $hoge_third\n"; ?>
$hoge_first = a $hoge_second = b $hoge_third = c
EXTR_PREFIX_ALLはEXTRA_PREFIX_ALLでないことに注意。
- compact()を使って、変数名をキーとした連想配列の作成
<?php $first = "a"; $second = "b"; $third = "c"; $hoge = compact("first" , "second" , "third"); print_r($hoge); ?>
Array ( [first] => a [second] => b [third] => c )