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

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.

Tags: 

Comments

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.