PHP Tutorial - PHP foreach






PHP has the following loop keywords: foreach, while, for, and do...while.

The foreach loop is designed to work with arrays. You can also use foreach with objects, in which case it iterates over each public variable of that object.

Syntax

The most basic use of foreach extracts only the values from each array element, like this:

foreach($array as $val) {
   print $val;
}

Here the array $array is looped through, and its values are extracted into $val. In this situation, the array keys are ignored completely.

You can also use foreach to extract keys, like this:

foreach ($array as $key => $val) {
   print "$key = $val\n";
}




Example

Loop array with foreach loop


<?PHP/*from  ww  w  . j  a v  a2 s .c o m*/
$list = array("A", "B", "C", "D", "E");

print "<ul>\n";
foreach ($list as $value){
  print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";

?>

The code above generates the following result.





Example 2

Iterating through a multidimensional array with foreach()


<?PHP//from   w  w w  . ja  va  2s .  co  m
$flavors = array('Japanese' => array('hot' => 'A',
                                     'salty' => 'B'),
                 'Chinese'  => array('hot' => 'D',
                                     'pepper-salty' => 'C'));

foreach ($flavors as $culture => $culture_flavors) {
    foreach ($culture_flavors as $flavor => $example) {
        print "A $culture $flavor flavor is $example.\n";
    }
}
?>

The code above generates the following result.

Example 3

Iterating Through Object Properties


<?PHP//  w  w  w  . ja  va 2s  .  c o  m
    class Person {
            public $FirstName = "Jack";
            public $MiddleName = "M.";
            public $LastName = "Smith";
            private $Password = "myPassword";
            public $Age = 29;
            public $HomeTown = "PHP";
            public $FavouriteColor = "Purple from java2s.com";
    }

    $bill = new Person( );

    foreach($bill as $key => $value) {
            echo "$key is $value\n";
    }
?>

The code above generates the following result.