PHP

Accessing All Elements of Numerical Arrays

array('I', 'II', 'III', 'IV');

Looping through numerical arrays can most easily be done using foreach because in each iteration of the loop, the current element in the array is automatically written in a variable.

Looping Through an Array with foreach

<?php
  $a = array('I', 'II', 'III', 'IV');
  foreach ($a as $element) {
    echo htmlspecialchars($element) . '<br />';
  }
?>

Alternatively, a for loop can also be used. The first array element has the index 0; the number of array indices can be retrieved using the count() function.

Looping Through an Array with for

<?php
  $a = array('I', 'II', 'III', 'IV');
  for ($i = 0; $i < count($a); $i++) {
    echo htmlspecialchars($a[$i]) . '<br />';
  }
?>

Both ways are equally good (or bad); though, usually, using foreach is the much more convenient way. However, there is a third possibility: The PHP function each() returns the current element in an array. The return value of each() is an array, in which you can access the value using the numerical index 1, or the string index 'value'. Using a while loop, the whole array can be traversed. The following code once again prints all elements in the array, this time using each().

Looping Through an Array with each()

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

The output of the three listings is always the same, of course.

by BrainBellupdated
Advertisement: