PHP

Turning an Array into Variables

while (list($key, $value) = each($a))

Whenever each() is used, the use of list() is a good idea. Within list(), you provide variable names for all values with numerical indices in the array that is returned by each(). This makes while/each() loops even easier to use, as the code shows. Within the parentheses, the variable names are provided.

Looping Through an Array with list() and each()

<?php
  $a = array('one' => 'I', 'two' => 'II', 'three' =>
    'III', 'four' => 'IV');
  while (list($key, $value) = each($a))  {
    echo htmlspecialchars("$key: $value") . '<br />';
  }
?>

If you are only interested in either the key or the value of the array, you can remove one of the two variables; just make sure that you keep the comma.

while (list(, $value) = each($a)) {
  echo htmlspecialchars("$value") .
     '<br />';
}

Note: The following examples are also functionally identical.

Looping Through an Array with foreach()

<?php
  $a = array('one' => 'I', 'two' => 'II', 'three' =>
    'III', 'four' => 'IV');
  foreach($a as $key => $value)  {
    echo htmlspecialchars("$key: $value") . '<br />';
  }
?>

If you are only interested in value of the array, you can remove =>.

foreach($a as $value)  {
    echo htmlspecialchars($value) . '<br />';
  }

by BrainBellupdated
Advertisement: