PHP Exam 2: Conditions, Loops, and Arrays (10 mixed exercises)
PHP Exam 2: Control Flow and Arrays
Test your ability to build logic with conditions and loops, and work with arrays.
Exercise 1
If/Else Statements
Check the time:
- Define `$hour` (24-hour format).
- If less than 12, print "Good morning".
- If between 12 and 18, print "Good afternoon".
- Otherwise, print "Good evening".
Solution
<?php
$hour = 14;
if ($hour < 12) {
echo "Good morning";
} elseif ($hour < 18) {
echo "Good afternoon";
} else {
echo "Good evening";
}
?>
Exercise 2
Switch
Choose a favorite color:
- Define `$favColor`.
- Use `switch` to check its value.
- If "red" print "Red", if "blue" print "Blue".
- Default case prints "Other color".
Solution
<?php
$favColor = "red";
switch ($favColor) {
case "red":
echo "Red";
break;
case "blue":
echo "Blue";
break;
default:
echo "Other color";
}
?>
Exercise 3
For Loop
Print numbers from 1 to 5:
- Use a `for` loop.
- Print each number on its own line.
Solution
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>
Exercise 4
While Loop
Count down from 5 to 1:
- Use a `while` loop.
- Print each number.
Solution
<?php
$count = 5;
while ($count >= 1) {
echo $count . "<br>";
$count--;
}
?>
Exercise 5
Foreach Loop
Loop through an array of names:
- Define `$names = ["Ali", "Sara", "Omar"]`.
- Use `foreach` to print each name.
Solution
<?php
$names = ["Ali", "Sara", "Omar"];
foreach ($names as $name) {
echo $name . "<br>";
}
?>
Exercise 6
Indexed Arrays
Work with an indexed array:
- Create `$fruits = ["Apple", "Banana", "Orange"]`.
- Print the second element.
- Add "Grape" to the array.
Solution
<?php
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[1]; // Banana
$fruits[] = "Grape";
print_r($fruits);
?>
Exercise 7
Associative Arrays
Create an associative array:
- Create `$user = ["name" => "Ali", "age" => 25]`.
- Print the name.
- Update the age to 26.
Solution
<?php
$user = ["name" => "Ali", "age" => 25];
echo $user["name"];
$user["age"] = 26;
print_r($user);
?>
Exercise 8
Array Functions
Use array functions:
- Count elements of `$numbers = [1, 2, 3, 4]`.
- Check if 3 exists in the array.
- Sort the array ascending.
Solution
<?php
$numbers = [1, 2, 3, 4];
echo count($numbers); // 4
var_dump(in_array(3, $numbers)); // true
sort($numbers);
print_r($numbers);
?>
Exercise 9
Nested Arrays
Work with a nested array:
- Create `$students = [["name" => "Ali"], ["name" => "Sara"]]`.
- Print the first student name.
Solution
<?php
$students = [["name" => "Ali"], ["name" => "Sara"]];
echo $students[0]["name"]; // Ali
?>
Exercise 10
Loop with Arrays
Loop through an associative array:
- Create `$product = ["name" => "Phone", "price" => 500]`.
- Use `foreach` to print each key and value.
Solution
<?php
$product = ["name" => "Phone", "price" => 500];
foreach ($product as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>