PHP foreach

In this chapter you will learn:

  1. What is foreach loop
  2. foreach loop Syntax
  3. Example - Loop array with foreach loop
  4. Example - Iterating through a multidimensional array with foreach
  5. Example - Iterating Through Object Properties

Description

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/* j a  v a  2  s  .c om*/
$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/*  ja v  a  2  s. c o  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//  ja v  a2s  .  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.

Next chapter...

What you will learn in the next chapter:

  1. What is PHP while loop
  2. Syntax for while loop
  3. Example - while loop with integer counter
  4. Example - Infinite Loops
  5. Example - infinite while loop with break statement
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require