Iterating Through an Array

You want to cycle through an array and operate on all or some of the elements inside.

Use foreach (PHP iterates over a copy of the array instead of the actual array):

foreach ($array as $value) {...
Or to get an array's keys and values:
foreach ($array as $key =>$value) {...
Or use for (PHP iterates over the original array):
// count() returns the size of the array for ($key = 0, $size = count($array); $key < $size; $key++) {...
Or use each() (PHP iterates over the original array) in combination with list() and while:
reset($array); // reset internal pointer to beginning of array
while (list($key, $value) = each($array)) {...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$fruits = array('Apples', 'Grapes', 'Bananas', 'Oranges');
// use foreach to loop through the array
echo "<p><b>Use foreach to get the values.</b></p>";
foreach ($fruits as $value) {
	echo "$value<br />";
}

// get keys and values
echo "<p><b>Use foreach to get the keys and values.</b></p>";
foreach ($fruits as $key => $value) {
	echo "$key:  $value<br />";
}

// Use the count function to find the number of elements in an array
echo "<p><b>Use for and count to get the values.</b></p>";
for ($key = 0, $size = count($fruits); $key < $size; $key++)
	echo "$fruits[$key]<br />";

// Use each() and list()
echo "<p><b>Use each() and list() to get the keys and values.</b></p>";
reset($fruits); // reset internal pointer to beginning of array
while (list($key, $value) = each($fruits)) {
	echo "$key:  $value<br />";
}
?>
</p>
</body>
</html>

View the effect


Arrays | What is an array? | Creating Arrays | Iterating | Not Beginning at 0 | Initializing to a Range | Modifying | Removing Elements | Removing Duplicate | Changing Size | Key in an Array | Element in an Array | Position of a Value | Largest or Smallest Element | Reversing | Randomizing
© 2008: Hann So
email: hso@voyager.deanza.edu