How to Loop through an Array

Q

How to Loop through an Array? - PHP Script Tips - Understanding PHP Arrays and Their Basic Operations

✍: FYIcenter.com

A

The best way to loop through an array is to use the "foreach" statement. There are two forms of "foreach" statements:

  • foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array.
  • foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.

Here is a PHP script on how to use "foreach" on an array:

<?php 
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$array["3"] = "C+";
$array[""] = "Basic";
$array[] = "Pascal";
$array[] = "FORTRAN";
print("Loop on value only:\n");
foreach ($array as $value) {
  print("$value, ");
}
print("\n\n");
print("Loop on key and value:\n");
foreach ($array as $key=>$value) {
  print("[$key] => $value\n");
}
?>

This script will print:

Loop on value only:
PHP, Perl, Java, C+, Basic, Pascal, FORTRAN,

Loop on key and value:
[Zero] => PHP
[One] => Perl
[Two] => Java
[3] => C+
[] => Basic
[4] => Pascal
[5] => FORTRAN

2007-04-20, 5054👍, 0💬