2 Control Structures And Loops

Web Technology II ยท Unit 2

Control Structures and Loops

Exam-focused notes for Control Structures and Loops (Web Technology II, BIT301): what the TU syllabus asks and how it has actually been tested, with 1 solved past questions from this unit.

Control Structures and Loops in short

Control structures decide which statements run and how many times. PHP uses the same ideas as C and Java: decisions, loops and jump statements.

Control Structures and Loops: notes

Conditional statements and switch statements

The if statement runs code only when a condition is true. It can have elseif and else parts.

<?php
$marks = 72;
if ($marks >= 80) {
    echo "Distinction";
} elseif ($marks >= 60) {
    echo "First division";
} elseif ($marks >= 40) {
    echo "Pass";
} else {
    echo "Fail";
}

The ternary operator gives a short form: $result = ($marks >= 40) ? "Pass" : "Fail";. The null coalescing operator ?? gives a default when a value is missing: $name = $_GET['name'] ?? "Guest";.

The switch statement compares one value with many cases. It is cleaner than a long elseif chain.

<?php
$day = 3;
switch ($day) {
    case 1:
        echo "Sunday";
        break;
    case 2:
        echo "Monday";
        break;
    case 3:
        echo "Tuesday";
        break;
    default:
        echo "Other day";
}
  • Each case should end with break, or the next case also runs (fall through).
  • default runs when no case matches.
  • switch uses loose comparison (==).
  • PHP 8 also has match, which uses strict comparison and returns a value.

What this unit covers

  • Conditional statements and switch statements
  • For loops and iteration
  • Foreach loops and array iteration
  • While and do while loops
  • Break and continue statements
  • Loop control flow

For loops and iteration

0 ยท 10 marks

What are casting operators? Differentiate for from foreach statement. Write PHP program to illustrate use of for and foreach.[10]

Show solved answer

Casting Operators, for vs foreach, and PHP Programs


1. Casting Operators

Casting operators are used to explicitly convert a value from one data type to another. In PHP, casting is done by placing the target type in parentheses before the variable or value.

Cast OperatorDescription
(int) or (integer)Converts to integer
(float) or (double)Converts to float
(string)Converts to string
(bool) or (boolean)Converts to boolean
(array)Converts to array
(object)Converts to object

Example:

<?php
  $x = 3.7;
  $y = (int)$x;      // $y = 3
  $z = (string)$x;   // $z = "3.7"
  echo $y;           // Output: 3
?>

2. Difference Between for and foreach

Featureforforeach
PurposeGeneral-purpose loop with counterSpecifically designed to iterate over arrays/objects
Syntaxfor(init; condition; increment)foreach($array as $value)
CounterRequires explicit counter variableNo counter needed
Use CaseWhen number of iterations is knownWhen iterating over all elements of an array
Index AccessUses numeric index manuallyCan access key and value directly
FlexibilityMore flexible, works with any conditionLess flexible, works mainly with arrays
ComplexitySlightly more complex syntaxSimpler and cleaner syntax
Array KeyMust access key manually ($arr[$i])Key available via foreach($arr as $key => $val)

3. PHP Program Illustrating for Loop

<?php
  // Using for loop to print numbers and sum of array elements

  echo "--- for loop: Print 1 to 5 ---\n";
  for ($i = 1; $i <= 5; $i++) {
      echo "Number: " . $i . "\n";
  }

  echo "\n--- for loop: Sum of array elements ---\n";
  $numbers = array(10, 20, 30, 40, 50);
  $sum = 0;

  for ($i = 0; $i < count($numbers); $i++) {
      $sum += $numbers[$i];
      echo "Element at index $i = " . $numbers[$i] . "\n";
  }

  echo "Sum = " . $sum . "\n";
?>

Output:

--- for loop: Print 1 to 5 ---
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

--- for loop: Sum of array elements ---
Element at index 0 = 10
Element at index 1 = 20
Element at index 2 = 30
Element at index 3 = 40
Element at index 4 = 50
Sum = 150

4. PHP Program Illustrating foreach Loop

<?php
  // Using foreach loop with indexed and associative arrays

  echo "--- foreach loop: Indexed Array ---\n";
  $fruits = array("Apple", "Banana", "Mango", "Orange");

  foreach ($fruits as $fruit) {
      echo "Fruit: " . $fruit . "\n";
  }

  echo "\n--- foreach loop: Associative Array (key => value) ---\n";
  $student = array(
      "Name"    => "Ram Kumar",
      "Roll"    => 101,
      "Course"  => "BSc CSIT",
      "Marks"   => 85
  );

  foreach ($student as $key => $value) {
      echo $key . " : " . $value . "\n";
  }
?>

Output:

--- foreach loop: Indexed Array ---
Fruit: Apple
Fruit: Banana
Fruit: Mango
Fruit: Orange

--- foreach loop: Associative Array (key => value) ---
Name : Ram Kumar
Roll : 101
Course : BSc CSIT
Marks : 85

Summary

  • Casting operators allow explicit type conversion in PHP.
  • for loop is best when the number of iterations is known and a counter is needed.
  • foreach loop is best for traversing arrays and objects cleanly without managing an index manually.
Open this answer on its own page โ†’