Home > Articles > Data > MySQL

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Accessing All Elements of Associative Arrays

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

Looping through an Associative Array with foreach (foreach-a.php)

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

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 shown 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':

<?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] 
  }
?>

Looping through an Associative Array with each (each-a.php)

  • + Share This
  • 🔖 Save To Your Account