Backend Development 2 min read

Understanding PHP foreach Loop Syntax and Usage

This tutorial explains PHP's foreach loop syntax, illustrating how to iterate over arrays with value-only and key‑value formats, and how to traverse object properties, accompanied by complete code examples for each case.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP foreach Loop Syntax and Usage

This article introduces the PHP foreach construct, describing its syntax for iterating over arrays and objects.

It first presents the two basic formats:

<code>foreach (array_expression as $value)
    statement;

foreach (array_expression as $key => $value)
    statement;</code>

Next, it demonstrates array traversal with two examples: a simple value‑only loop and a key‑value loop, showing complete PHP code snippets and the expected output.

<code><?php
$arr = array(1, 2, 3, 4, 7, 8, 9, 10, 11);
foreach($arr as $a) {
    echo $a,'<br/>'; // 1 2 3 4 7 8 9 10 11
}
?>
</code>
<code><?php
$arr = array(1, 2, 3, 4, 7, 8, 9, 10, 11);
foreach($arr as $a => $v) {
    echo 'key',$a,'== value',$v,'<br/>';
}
// key0== value1
// key1== value2
// ...
?>
</code>

Finally, the article explains how foreach can iterate over an object's public properties, providing a class definition and a loop that prints each property name and its value.

<code><?php
// Define class
class Man {
    public $name = 'LiLei';
    public $height = 178;
    public $weight = 140;
    protected $age = 30;
    private $money = 1000;
}

// Instantiate
$m = new Man();

// Iterate
foreach($m as $k => $v){
    echo $k . ' : ' . $v . '<br/>'; // $k is property name, $v is value
}
/* Output:
name : LiLei
height : 178
weight : 140
*/
?>
</code>
Backend Developmentforeacharray iterationobject iteration
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.