Page 1 of 1

How to Loop through an Array?

Posted: Sat Oct 01, 2016 5:25 pm
by deepak singh
How to Loop through an Array?

Re: How to Loop through an Array?

Posted: Sat Oct 01, 2016 5:26 pm
by rameshkhd
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