Expert Refresh

Key-value

1) How do you assign variables as if they were an array?





2) How do you get the current key/value pair?







list() - assign variables as if they were array <?php // Atention: Assigns the values starting with the right-most parameter // Example 1 list($a, $b) = array(1, 2); echo $a; // Output: 1 echo $b; // Output: 2 // Example 2 $a = array(); list($a[0], $a[1], $a[2]) = array(1, 2, 3); print_r($a); // Array ( [2] => 3 [1] => 2 [0] => 1 ) each() - return current key/value and advance the cursor <?php // Example 1 $arr = array(1,2,3); $res = each($arr); print_r($res); // Array ( [1] => 1 [value] => 1 [0] => 0 [key] => 0 ) echo $res['value']; // Output: 1 // Example 2 $arr = array('a', 'b', 'c'); while(list($k, $v) = each($arr)) { echo $k . $v; } // 0a 1b 2c extract() - assign variable from key/value <?php $array = array('a'=>1, 'b'=>2, 'c'=>3); extract($array); echo $b; // Output: 2


References