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:

foreach (array_expression as $value)
    statement;

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

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.

<?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
}
?>
<?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
// ...
?>

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.

<?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
*/
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.