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;

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);

If you have a question, put $5 at patreon and message me.

  1. PHP Install
  2. PHP Basics
  3. String Syntax
  4. String Operations
  5. Array
  6. Hash Table
  7. Looping Thru Array
  8. Function
  9. Write Package
  10. Send HTML Mail
  11. Send Mail with Attachment
  12. MySQL Database Query