PHP: Looping Thru Array

By Xah Lee. Date:

Loop Thru Values

To go thru a list, use “foreach”. Here's a example of looping thru a list and accessing its values:

<?php
$aa = array("nil","bi","tri");
foreach ($aa as $x) {
  echo "$x ";
} // prints nil bi tri

Loop Thru Keys and Values

Here's a example of looping thru a list and accessing both keys and values:

<?php
$aa = array("nil","bi","tri");
foreach ($aa as $k => $v) {
  echo "$k,$v;  ";
} // prints 0,nil;  1,bi;  2,tri;

foreach

Map Thru Values

Map a function to a array.

<?php
function ff($n) {return($n+1);}

$a = array(3,9,4);
$b = array_map(ff, $a); // $b is (4,10,5)
print_r($b);

array-map

2007-11