human growth hormone side effects
Webmaster Resources
 

Assigning name/value pair from a single element array to variables

Thursday May 26, 2011

How do you extract name/value pair of an associative array into PHP variables? Whether it’s a single element array, or multiple element array the procedure is identical.

$coins = array(“penny” => 1, “nickle” => 5, “dime” => 10, “quarter” => 25);
foreach ($coins as $name => $value) {
echo “$name -> $value\n”;
}

while(list($name, $value) = each($coins)) {
echo “$name -> $value\n”;
}

If you have a multi-dimentional array with a single element in an array for multi-element relationship (name/name/value, or name/value/value), you may use the following:

$family = array(
“dad” => array(“scott” => 45),
“mom” => array(“karen” => 43),
“son1″ => array(“ryan” => 16),
“daughter” => array(“cindy” => 18),
“son2″ => array(“andrew” => 13));

foreach($family["dad"] as $name => $age);
echo “(Dad) name: $name, age: $age\n”;

list($name, $age) = each($family["mom"])
echo “(Mom) name: $name, age: $age\n”;

Basically, the foreach and list/each commands achieve the same goal.

Did you like this? Share it:
Leave a Reply

Comment

*