Skip to content

Chapter 8 of 38

Loops

Repeat work with for, while, do-while, foreach, break, and continue.

30 minutes 10 quick checksBy Subha Prasad
Lesson 8 of 38Course navigation

Lesson content

Read, practise, then check your understanding

Use for for counting, while for condition-controlled work, do-while when one pass is required, and foreach for arrays and Traversable values.

Practical example

<?php
$scores = ['Mira' => 91, 'Ari' => 76];
foreach ($scores as $name => $score) { echo "$name: $score\n"; }
for ($i = 0; $i < 3; $i++) { if ($i === 1) continue; }

Reference iteration mutates elements but leaves the loop variable referencing the final element; unset it afterward or avoid the pattern. Bound external-data loops, check termination, and consider algorithmic complexity before nesting.

Knowledge check

Answer every question correctly to complete this chapter.

Which statement best describes for?
Which PHP term matches this description: A loop with initialization, condition, and update clauses.
Which statement best describes while?
Which PHP term matches this description: A loop testing before each iteration.
Which statement best describes do-while?
Which PHP term matches this description: A loop executing its body at least once.
Which statement best describes foreach?
Which PHP term matches this description: Iteration over array values and optionally keys.
Which statement best describes break?
Which PHP term matches this description: Immediate exit from a loop or switch level.

0 of 10 checks passed

Your progress is saved on this device.