What is the primary use of the `foreach` loop in PHP?
A
Iterating over numbers B
Iterating over arrays C
Creating functions D
Handling errors
Analysis & Theory
`foreach` is specifically designed to loop through arrays in PHP.
What is the correct syntax of a `foreach` loop?
A
foreach array as key => value { } B
foreach(array as key => value) { } C
foreach (array key => value) { } D
foreach -> array (key, value) { }
Analysis & Theory
Correct syntax: `foreach(array as key => value) { // code }`.
What is the output?
```
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color;
}
?>
```
A
redgreenblue B
red green blue C
array D
Error
Analysis & Theory
It prints `redgreenblue` because there is no space or newline in `echo`.
Can `foreach` loop be used with associative arrays?
A
No B
Yes C
Only with numeric arrays D
Only in functions
Analysis & Theory
Yes, `foreach` works with both indexed and associative arrays.
What is the output?
```
<?php
$age = array("John" => 25, "Jane" => 30);
foreach ($age as $name => $years) {
echo $name . " is " . $years . " years old. ";
}
?>
```
A
John is 25 years old. Jane is 30 years old. B
25 John 30 Jane C
Error D
Nothing
Analysis & Theory
The loop prints both key and value for each item in the associative array.
What happens if you use `foreach` on an empty array?
A
It runs forever B
It throws an error C
It runs once D
It does not run
Analysis & Theory
If the array is empty, `foreach` does not execute its block.
Can you modify array elements inside a `foreach` loop?
A
No B
Yes, using reference `&` C
Only with functions D
Only with while loop
Analysis & Theory
Yes, using `foreach($array as &$value)`, modifications affect the original array.
What is the output?
```
<?php
$nums = array(1, 2, 3);
foreach ($nums as $num) {
echo $num * 2;
}
?>
```
A
246 B
123 C
Error D
2 4 6
Analysis & Theory
It multiplies each number by 2 and prints `246`.
Is it possible to nest a `foreach` loop inside another `foreach` loop?
A
No B
Yes C
Only in functions D
Only with if
Analysis & Theory
Yes, nested `foreach` loops are often used for multidimensional arrays.
Which keyword stops a `foreach` loop immediately?
A
exit B
stop C
break D
end
Analysis & Theory
`break` is used to exit the `foreach` loop immediately.