How to Loop through an Array?

deepak singh
Posts: 686
Joined: Fri Sep 30, 2016 4:19 pm

How to Loop through an Array?

Postby deepak singh » Sat Oct 01, 2016 5:25 pm

How to Loop through an Array?

rameshkhd
Posts: 1279
Joined: Sun Aug 28, 2016 10:45 am

Re: How to Loop through an Array?

Postby rameshkhd » Sat Oct 01, 2016 5:26 pm

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


Return to “PHP”

Who is online

Users browsing this forum: No registered users and 1 guest