Comprehensive Guide to PHP foreach Loop with Examples
This article thoroughly explains PHP's foreach loop syntax, demonstrates its use with indexed, associative, and multidimensional arrays, and provides complete code examples showing how to access values and keys in each scenario.
This article provides a detailed tutorial on using the foreach construct in PHP, covering both of its syntaxes and illustrating each with practical array examples.
foreach syntax
Two forms are available:
1. foreach (array_expression as $value) – iterates over the array, assigning each element's value to $value .
2. foreach (array_expression as $key => $value) – in addition to the value, the current element's key is assigned to $key .
1. One‑dimensional indexed array
<code>$a = array('Tom','Mary','Peter','Jack');</code>Using the first syntax:
<code>foreach ($a as $value) {
echo $value . "\n";
}</code>Output:
<code>Tom
Mary
Peter
Jack</code>Using the second syntax:
<code>foreach ($a as $key => $value) {
echo $key . ',' . $value . "\n";
}</code>Output:
<code>0,Tom
1,Mary
2,Peter
3,Jack</code>2. One‑dimensional associative array
<code>$b = array('a'=>'Tom','b'=>'Mary','c'=>'Peter','d'=>'Jack');</code>First syntax (value only):
<code>foreach ($b as $value) {
echo $value . "\n";
}</code>Second syntax (key and value):
<code>foreach ($b as $key => $value) {
echo $key . ',' . $value . "\n";
}</code>Output shows that $key corresponds to the associative keys a, b, c, d .
3. Two‑dimensional indexed array
<code>$c = array(
array('1','Tom'),
array('2','Mary'),
array('3','Peter'),
array('4','Jack')
);</code>First syntax (value only):
<code>foreach ($c as $value) {
print_r($value);
echo "\n";
}</code>Second syntax (key and value):
<code>foreach ($c as $key => $value) {
echo '$key=' . $key . "\n";
print_r($value);
echo "\n";
}</code>In this case $key is the numeric index 0‑3.
4. Two‑dimensional associative array
<code>$d = array(
array('id'=>'11','name'=>'Tom'),
array('id'=>'22','name'=>'Mary'),
array('id'=>'33','name'=>'Peter'),
array('id'=>'44','name'=>'Jack')
);</code>First syntax (value only) prints each sub‑array; the second syntax also provides the numeric $key (0‑3) while the sub‑array contains named fields id and name .
Overall, the tutorial demonstrates how foreach can iterate over different array structures, how to retrieve values alone or both keys and values, and how the key reflects either numeric indices or associative identifiers depending on the array type.
Note: The author invites readers to leave questions in the comments for future answers.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.