PHP

Accessing All Elements of Associative Arrays

foreach ($array as $key => $value) {

When using an associative array and wanting to access all data in it, the keys are also of relevance. For this, the foreach loop must also provide a variable name for the element's key, not only for its value.

Looping Through an Associative Array with foreach

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

Using count() is possible: count() returns the number of values in the array, not the number of elements. Looping through all array elements with for is not feasible. However, the combination of each() and while can be used, as can be seen in the following code. The important point is that the key name can be retrieved either using the index 0 or the string index 'key'.

Looping Through an Array with each()

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

by BrainBellupdated
Advertisement: