Control structures and arrays: if/else/elseif/switch; for, while, do-while, foreach; arrays (indexed, associative, multidimensional); array operations (sort(), asort(), ksort(), array_merge())

PHP's control flow is familiar, but its arrays are the star: indexed, associative (key to value) and multidimensional, walked with foreach, and reshaped by a rich family of array functions.

12 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The registration list is an array

The event portal's core data is a LIST: everyone registered for Garba Night. In PHP that list is an array, and PHP's arrays are unusually powerful: they can be simple numbered lists, or maps from keys to values, or nested tables of records.

Control flow (if, switch, loops) you already know from 5 languages; PHP's versions hold few surprises. So this lesson spends its energy where PHP is genuinely distinctive and exam-heavy: arrays, the loop that walks them (foreach), and the family of functions that sort and reshape them.

Theory

Control flow, briefly

PHP's control structures are the familiar set:

  • if / elseif / else and switch (with break per case) for decisions
  • for, while, do-while for counted and conditional loops
  • foreach for walking arrays: the one worth real attention

foreach comes in 2 forms: foreach ($arr as $value) to visit each value, and foreach ($arr as $key => $value) to visit each key AND its value. For associative arrays (below), the second form is essential.

Theory

Three kinds of array

PHP arrays come in 3 shapes:

  • Indexed: numeric keys from 0. $names = ["Riya", "Aman"]; so $names[0] is "Riya"
  • Associative: STRING keys mapping to values. $event = ["seats" => 350, "venue" => "Ground"]; so $event["seats"] is 350
  • Multidimensional: arrays of arrays, perfect for a table of records: a registration list where each entry is itself an associative array of one person's details

The associative array is PHP's signature strength: a built-in map (like a dictionary) with clean key => value syntax.

Practical

Arrays and foreach (predict the output)

<?php
  // Associative array: keys map to values
  $event = ["venue" => "Ground", "seats" => 350, "fee" => 50];

  foreach ($event as $key => $value) {
    echo "$key = $value <br>";
  }
  // venue = Ground
  // seats = 350
  // fee = 50

  // Multidimensional: a registration list
  $regs = [
    ["name" => "Riya", "paid" => true],
    ["name" => "Aman", "paid" => false],
  ];
  echo $regs[0]["name"];   // Riya
  echo count($regs);        // 2
?>

At a glance

The sorting family (the exam favourite)

FunctionSorts byKeeps key association?
sort()Values, ascendingNo: re-indexes 0,1,2 (keys lost)
asort()Values, ascendingYes: keeps key => value pairs
ksort()Keys, ascendingYes: reorders by key
rsort() / arsort() / krsort()The above, descendingSame as their ascending twins

Quiz

You have an associative array $scores = ["Riya"=>80, "Aman"=>95]. You want to sort by score BUT keep each name attached to its score. Which function?

  1. sort(): it sorts the values
  2. asort(): it sorts by value while keeping the key => value association
  3. ksort(): it sorts by key
  4. array_merge(): it combines arrays
Show the answer

asort(): it sorts by value while keeping the key => value association

asort() sorts by VALUE (the scores) but PRESERVES the key-value pairs, so Riya stays attached to 80 and Aman to 95: exactly what you need. sort() would also order the values but RE-INDEXES the array to 0,1,2, DESTROYING the name keys: you would lose who scored what. ksort() sorts by the KEYS (names alphabetically), not the scores. array_merge() does not sort at all. This sort-vs-asort distinction (does it keep keys?) is the most-asked PHP array question: sort loses keys, asort keeps them.

Think first

sort() destroyed the map

A student runs sort() on the $scores associative array to order by score, then loops with foreach($scores as $name => $score). The names come out as 0 and 1, not Riya and Aman. Explain what happened, then tap.

Show the answer

sort() sorts the VALUES ascending but also RE-INDEXES the array with fresh numeric keys 0, 1, 2..., THROWING AWAY the original string keys. So after sort(), the array is [0=>80, 1=>95]: the names are gone, replaced by numbers, and the foreach now sees keys 0 and 1. The fix is asort(), which sorts by value while KEEPING the name keys attached. The lesson: on associative arrays, choose the sort function by whether you must preserve keys: sort/rsort discard them, asort/arsort/ksort/krsort keep them. Reach for sort() only on plain indexed lists where keys do not matter.

Watch out

Array traps

sort() on associative arrays: it destroys the keys; use asort() to keep them.

foreach without key => value: on an associative array you need as $key => $value to see the keys.

Off-by-one on count(): count() gives the number of elements; the last index is count() - 1 for indexed arrays.

Undefined keys: accessing $arr["missing"] warns and gives null; check with isset() first.

Modifying an array while foreaching it: can cause subtle bugs; build a new array instead.

Theory

Data and logic done; now real input

The portal can now store its registration list as a multidimensional array, walk it with foreach, and sort it any way needed. But the data has to come from somewhere: a user filling a FORM. The next lesson connects HTML forms to PHP with $_GET and $_POST, wraps repeated logic in FUNCTIONS, and adds the input validation and sanitization every real login form requires. Unit 1 ends where the portal comes alive: handling a real registration.

Summary

Key takeaways

  • Control flow is familiar: if/elseif/else, switch (with break), for, while, do-while, and foreach for arrays.
  • foreach walks arrays: as $value for values, as $key => $value for key-value pairs.
  • Three array kinds: indexed (numeric keys from 0), associative (string key => value), multidimensional (arrays of arrays).
  • Associative arrays are PHP's built-in maps; multidimensional arrays model tables of records (the registration list).
  • Sorting: sort() orders values but RE-INDEXES (loses keys); asort() keeps key-value pairs; ksort() sorts by key.
  • Choose the sort function by whether you must preserve keys.
  • Memory hook: sort loses keys, asort keeps them.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Core PHP Programming

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Control structures and arrays: if/else/elseif/switch; for, while, do-while, foreach; arrays (indexed, associative, multidimensional); array operations (sort(), asort(), ksort(), array_merge()) · Web Framework and Services (Major-12) · Gri-Learn