Preparing your PDF
Loading PDF viewer...
Semester
Subject
Introduction
for and foreach Loop with ProgramPHP is called a loosely typed language because it does not require the programmer to declare the data type of a variable. The type is automatically determined at runtime based on the value assigned to it.
Key Points:
Example:
$x = 10; // $x is an integer
$x = "Hello"; // now $x is a string
$x = 3.14; // now $x is a float
In strongly typed languages like Java or C, you must declare int x = 10; and cannot later assign a string to x. PHP removes this restriction, making it loosely typed.
for Loop and foreach Loop| Feature | for Loop |
foreach Loop |
|---|---|---|
| Purpose | Used when number of iterations is known | Used to iterate over arrays/collections |
| Syntax | Requires initialization, condition, increment | Requires only the array variable |
| Index Control | Programmer manually controls the index | Automatically accesses each element |
| Use Case | Counting, repetition-based tasks | Traversing all elements of an array |
| Risk | May cause infinite loop if condition is wrong | Always terminates after last element |
<?php
// Demonstrating for loop
echo "Using for loop: <br>";
for($i = 1; $i <= 5; $i++) {
echo "Number: " . $i . "<br>";
}
echo "<br>";
// Demonstrating foreach loop
echo "Using foreach loop: <br>";
$fruits = array("Apple", "Banana", "Mango", "Orange", "Grapes");
foreach($fruits as $fruit) {
echo "Fruit: " . $fruit . "<br>";
}
echo "<br>";
// foreach with key-value pairs
echo "Using foreach with key-value: <br>";
$marks = array("Math" => 90, "Science" => 85, "English" => 78);
foreach($marks as $subject => $score) {
echo $subject . " = " . $score . "<br>";
}
?>
Output:
Using for loop:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Using foreach loop:
Fruit: Apple
Fruit: Banana
Fruit: Mango
Fruit: Orange
Fruit: Grapes
Using foreach with key-value:
Math = 90
Science = 85
English = 78
PHP's loosely typed nature makes it flexible and beginner-friendly. The for loop is best for counter-based iteration, while foreach is specifically designed for traversing arrays efficiently without manual index management.