PHP Array foreach loop

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 ) { /*ww  w .ja  v  a 2s . c o 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 w w  w  . j a  va  2  s . c  o  m
// (rest of script here)   

Example 1

Use foreach loop to get value


<?PHP// w ww . j  ava2  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   www.  ja v  a 2  s  .  c  o 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.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone