foreach
Use this to loop through each element of an array (or iterator). It resets the array pointer to the first element automatically for you and goes through to the last element.
As mentioned before, these next two loops are identical but use foreach to do this.
$arr = array( 'apple', 'x' => 'banana', 'eat' => 'carrot', 'durian' ); while( list( $key, $val ) = each( $arr ) ) { echo "$key => $val\n"; } /* 0 => apple x => banana eat => carrot 1 => durian */ foreach( $arr as $key => $val ) { echo "$key => $val\n"; } /* 0 => apple x => banana eat => carrot 1 => durian */
You can either get both the key and value by using the syntax shown above, or just the value as shown below.
<?php $arr = array( 'apple', 'x' => 'banana', 'eat' => 'carrot', 'durian' ); foreach( $arr as $val ) { echo "$val\n"; } /* apple banana carrot durian */
Note that an array’s elements get their order from the order they were assigned - not necessarily the numerical order of the keys.
$arr = array( 7 => 'apple', 0 => 'banana' ); $arr[2] = 'eat'; foreach( $arr as $key => $val ) { echo "$val\n"; } /* apple banana eat */
See the manual entry for foreach
