Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Practical 5 (Part 4): foreach Loop

Lesson 9 of 35 in the free Web Based Programming Lab notes on Siksha Sarovar, written by Rohit Jangra.

Aim

To traverse a PHP array with the foreach loop, the idiomatic construct for iterating arrays and other traversable structures without manual index bookkeeping.

Theory

foreach ($array as $value) visits every element of an array in insertion order; the richer form foreach ($array as $key => $value) also exposes each element's key. Why it is preferred over an index-based for for arrays:

  • It works uniformly on associative arrays, where numeric indexing is meaningless.
  • There is no counter to get wrong — no off-by-one class of bugs.
  • It iterates anything that is an array or implements Traversable (e.g. Iterator objects, generators, PDO result sets).

Semantics worth knowing at the advanced level:

  • Copy semantics: $value receives a copy of each element — assigning to $value does not modify the array.
  • Reference form: foreach ($arr as &$value) makes $value an alias, so writes mutate the array in place. Classic pitfall: the reference survives the loop, so a later plain foreach can silently overwrite the last element — always unset($value); after a by-reference loop.
  • Keys of a list-style array are 0, 1, 2, ...; foreach follows insertion order, not sorted key order.
  • break/continue work exactly as in other loops.

Requirements

  • XAMPP/WAMP with PHP 8.x, or PHP CLI
  • Code editor and a browser/terminal

Procedure

  1. Start Apache from the XAMPP Control Panel.
  2. Save the snippet as p05d_foreach.php in C:\xampp\htdocs\wbplab.
  3. Run http://localhost/wbplab/p05d_foreach.php or php p05d_foreach.php.
  4. Extend the experiment: switch to foreach ($fruits as $index => $fruit) and print $index: $fruit; then try an associative array like ["a" => "Apple"] to see string keys.

Explanation of the Code

  • $fruits = ["Apple", "Banana", "Cherry"]; builds an indexed array using short array syntax; implicit keys are 0, 1, 2.
  • foreach ($fruits as $fruit) starts a traversal: on each pass PHP copies the next element into $fruit — first "Apple", then "Banana", then "Cherry".
  • The body echo $fruit . " "; prints the copy followed by a space; because $fruit is a copy, writing $fruit = "Mango"; inside the loop would leave $fruits untouched.
  • The loop ends automatically after the last element — no condition or counter management exists to maintain.

Expected Output

FOREACH LOOP:
Apple Banana Cherry

The three fruits print on one line, space-separated, in insertion order.

🎯 Viva Questions

  1. Does assigning to $value inside foreach change the array? No — $value is a copy unless declared with &.
  2. What is the danger of foreach ($arr as &$v)? The reference outlives the loop; without unset($v), a later loop can corrupt the last element.
  3. How do you access keys during traversal? Use the foreach ($arr as $key => $value) form.
  4. In what order does foreach visit elements? Insertion order of the array, regardless of key values.
  5. What besides arrays can foreach iterate? Any Traversable — objects implementing Iterator/IteratorAggregate, and generators.
  6. When is a classic for still better for arrays? When you need index arithmetic, e.g. comparing $a[$i] with $a[$i + 1] in sorting algorithms.

CO Mapping

CO1, CO2