PHP Array foreach loop

In this chapter you will learn:

  1. How to use foreach to loop through an array
  2. Syntax to get value using foreach loop
  3. Syntax to get key and value using foreach loop
  4. Example - Use foreach loop to get value
  5. Example - Use foreach to loop through associate array

Description

foreach is a special kind of looping statement that works only on arrays and objects.

foreach can be used in two ways.

  • retrieve just the value of each element, or
  • retrieve the element's key and value.

Syntax to get value

Use foreach to retrieve each element's value, as follows:


foreach ( $array as $value ) { /*from jav a2 s . co  m*/
   // (do something with $value here) 
} 
// (rest of script here)   

Syntax to get key and value

To use foreach to retrieve both keys and values, use the following syntax:


foreach ( $array as $key =>  $value ) { 
   // (do something with $key and/or $value here 
} //from  ja  va 2s  .c o  m
// (rest of script here)   

Example 1

Use foreach loop to get value


<?PHP/* ja va  2  s  .c  o  m*/
   $authors = array( "Java", "PHP", "CSS", "HTML" ); 

   foreach ( $authors as $val ) { 
       echo $val . "\n"; 
   }   
?>

The code above generates the following result.

Example 2

Use foreach to loop through associate array


<?php //from  jav a2s.  co  m
$myBook = array( "title" =>  "Learn PHP from java2s.com", 
                "author" =>  "java2s.com", 
                "pubYear" =>  2000 ); 

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

?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Why the value is not changed in foreach loop
  2. How to change the value inside a foreach loop
  3. Syntax to get value reference in a foreach loop
  4. Example - change array value with reference in foreach loop
  5. Note for unset value
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array