PHP Loops and Control Structures
PHP Loops and Control Structures Interview with follow-up questions
1. What are the different types of loops in PHP?
PHP has four loop constructs:
1. for loop — use when the number of iterations is known
for ($i = 0; $i < 10; $i++) {
echo $i;
}
2. while loop — use when iterating until a condition changes
$i = 0;
while ($i < 10) {
echo $i++;
}
3. do...while loop — like while, but always executes the body at least once
$i = 0;
do {
echo $i++;
} while ($i < 10);
4. foreach loop — designed for arrays and objects implementing Traversable; the most commonly used loop in modern PHP
$fruits = ['apple', 'banana', 'mango'];
foreach ($fruits as $fruit) {
echo $fruit;
}
// With key => value
$prices = ['apple' => 1.2, 'banana' => 0.5];
foreach ($prices as $item => $price) {
echo "$item: $price";
}
Interview additions:
foreachwith generators is memory-efficient for large datasets — the generator yields one value at a time instead of loading all data into an array.array_walk(),array_map(), andarray_filter()are functional alternatives to explicit loops for transforming or filtering arrays.- PHP 8.4 added
array_find()andarray_any()/array_all()as convenient alternatives to loops for searching arrays.
Follow-up 1
Can you explain how a 'for' loop works in PHP?
A 'for' loop in PHP allows you to execute a block of code a specified number of times. It consists of three parts: initialization, condition, and increment/decrement. Here's an example:
for ($i = 0; $i < 5; $i++) {
echo $i;
}
This loop will output the numbers from 0 to 4.
Follow-up 2
What is the difference between 'while' and 'do-while' loops in PHP?
The main difference between 'while' and 'do-while' loops in PHP is that a 'while' loop checks the condition before executing the code block, while a 'do-while' loop checks the condition after executing the code block. This means that a 'do-while' loop will always execute the code block at least once. Here's an example:
$i = 0;
while ($i < 5) {
echo $i;
$i++;
}
$i = 0;
do {
echo $i;
$i++;
} while ($i < 5);
Both of these loops will output the numbers from 0 to 4.
Follow-up 3
How would you break out of a loop in PHP?
To break out of a loop in PHP, you can use the 'break' statement. When the 'break' statement is encountered, the loop is immediately terminated and the program execution continues with the next statement after the loop. Here's an example:
for ($i = 0; $i < 10; $i++) {
if ($i === 5) {
break;
}
echo $i;
}
This loop will output the numbers from 0 to 4, and then break out of the loop when the value of 'i' is 5.
Follow-up 4
Can you give an example of a 'foreach' loop in PHP?
A 'foreach' loop in PHP is used to iterate over arrays or objects. It automatically assigns the current value of the array or object to a variable, which can be used inside the loop. Here's an example:
$fruits = array('apple', 'banana', 'orange');
foreach ($fruits as $fruit) {
echo $fruit;
}
This loop will output the values 'apple', 'banana', and 'orange' on separate lines.
2. What are control structures in PHP?
Control structures in PHP direct the flow of execution — which code runs, how many times, and in what order.
Conditional structures:
if / elseif / else— execute code based on a boolean conditionswitch— compare one value against multiple cases; uses loose comparison (==)match(PHP 8.0+) — likeswitchbut uses strict comparison (===), returns a value, and throwsUnhandledMatchErroron no match
// match expression (preferred over switch for simple value comparison)
$label = match($status) {
1 => 'Active',
2, 3 => 'Pending',
default => 'Unknown',
};
Loop structures:
for,while,do...while,foreach— repeat a block of code
Jump statements:
break— exit the current loop or switchcontinue— skip to the next iterationreturn— exit the current functionthrow— raise an exception (can be used as an expression in PHP 8.0+)
Null coalescing and ternary (conditional expressions):
$name = $_GET['name'] ?? 'Guest'; // null coalescing
$label = $active ? 'Yes' : 'No'; // ternary
$value = $a ??= 'default'; // null coalescing assignment (PHP 7.4+)
Interview tip: Interviewers often ask about match vs switch. Key differences: match does strict type comparison, always returns a value, has no fall-through, and throws on unmatched input (no silent default behavior).
Follow-up 1
What is the use of 'if' statement in PHP?
The 'if' statement in PHP is used to execute a block of code if a specified condition is true. It allows you to perform different actions based on different conditions.
Follow-up 2
Can you explain the 'switch' statement in PHP?
The 'switch' statement in PHP is used to perform different actions based on different conditions. It is similar to a series of 'if' statements, but provides a more concise way to handle multiple conditions.
Follow-up 3
How does the 'else if' statement work in PHP?
The 'else if' statement in PHP is used to add additional conditions to an 'if' statement. It allows you to check for multiple conditions and execute different code blocks based on those conditions.
Follow-up 4
Can you give an example of using 'switch' statement in PHP?
Sure! Here's an example of using the 'switch' statement in PHP:
$day = 'Monday';
switch ($day) {
case 'Monday':
echo 'Today is Monday';
break;
case 'Tuesday':
echo 'Today is Tuesday';
break;
case 'Wednesday':
echo 'Today is Wednesday';
break;
default:
echo 'Today is not Monday, Tuesday, or Wednesday';
}
This example checks the value of the variable $day and executes different code blocks based on the value. In this case, it will output 'Today is Monday'.
3. How can you iterate over an array in PHP?
The most common way to iterate over an array is with foreach:
$fruits = ['apple', 'banana', 'orange'];
// Values only
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Keys and values (indexed array)
foreach ($fruits as $index => $fruit) {
echo "$index: $fruit\n";
}
// Associative array
$prices = ['apple' => 1.20, 'banana' => 0.50];
foreach ($prices as $name => $price) {
echo "$name costs \${$price}\n";
}
Modifying array values during iteration:
foreach ($numbers as &$num) {
$num *= 2; // modifies the original array
}
unset($num); // always unset the reference after the loop — a common gotcha
Functional alternatives (preferred for transformations):
$doubled = array_map(fn($n) => $n * 2, $numbers);
$evens = array_filter($numbers, fn($n) => $n % 2 === 0);
$sum = array_reduce($numbers, fn($carry, $n) => $carry + $n, 0);
Iterating with generators (memory efficient for large datasets):
function readLines(string $file): Generator {
$fh = fopen($file, 'r');
while (($line = fgets($fh)) !== false) {
yield trim($line);
}
fclose($fh);
}
foreach (readLines('/path/to/large.csv') as $line) {
// process one line at a time without loading the whole file
}
PHP 8.4: array_find() returns the first element matching a callback; array_any() and array_all() provide boolean checks over arrays.
Follow-up 1
What is the difference between 'for' and 'foreach' when iterating over an array?
The main difference between 'for' and 'foreach' when iterating over an array in PHP is the way you access the elements. In a 'for' loop, you need to use the index of the array to access each element, while in a 'foreach' loop, you can directly access the element without the need for an index variable.
Here is an example to illustrate the difference:
$fruits = ['apple', 'banana', 'orange'];
// Using a for loop
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . '\n';
}
// Using a foreach loop
foreach ($fruits as $fruit) {
echo $fruit . '\n';
}
Both of these examples will output the same result:
apple
banana
orange
Follow-up 2
Can you give an example of iterating over an associative array in PHP?
Yes, in PHP, you can also iterate over an associative array using the 'foreach' loop. An associative array is an array that uses named keys instead of numeric indices. Here is an example:
$person = [
'name' => 'John Doe',
'age' => 25,
'email' => '[email protected]'
];
foreach ($person as $key => $value) {
echo $key . ': ' . $value . '\n';
}
This will output:
name: John Doe
age: 25
email: [email protected]
Follow-up 3
What happens if you try to iterate over a non-array variable using 'foreach' in PHP?
If you try to iterate over a non-array variable using 'foreach' in PHP, you will get a warning message and the loop will not be executed. This is because 'foreach' can only be used to iterate over arrays.
Here is an example:
$number = 10;
foreach ($number as $value) {
echo $value . '\n';
}
This will result in a warning message like:
Warning: Invalid argument supplied for foreach() in ...
4. What is the purpose of 'break' and 'continue' statements in PHP?
break and continue modify loop execution flow:
break — immediately exits the innermost loop (or switch), and execution continues after the loop body.
foreach ($users as $user) {
if ($user['role'] === 'admin') {
$adminUser = $user;
break; // stop searching once found
}
}
break accepts an optional integer argument to break out of nested loops:
foreach ($matrix as $row) {
foreach ($row as $cell) {
if ($cell === 'target') {
break 2; // exit both the inner and outer foreach
}
}
}
continue — skips the remaining statements in the current loop iteration and moves to the next iteration.
foreach ($orders as $order) {
if ($order['status'] === 'cancelled') {
continue; // skip cancelled orders
}
processOrder($order);
}
Like break, continue accepts an integer to skip levels in nested loops.
Interview tip: Overuse of break and continue with numeric arguments can make code hard to follow. In modern PHP, refactoring into smaller functions that use return early is generally preferred over multi-level break/continue. Functional approaches (array_filter, array_find) also reduce the need for explicit loop control.
Follow-up 1
Can you give an example of using 'break' in a PHP loop?
Sure! Here's an example of using 'break' in a PHP loop:
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . ' ';
}
In this example, the loop starts from 1 and iterates up to 10. However, when the value of $i becomes 5, the 'break' statement is encountered and the loop is terminated. As a result, only the numbers 1, 2, 3, and 4 will be echoed.
Follow-up 2
How does 'continue' statement affect the loop execution?
The 'continue' statement affects the loop execution by skipping the rest of the current iteration and moving on to the next iteration. Here's an example to illustrate its usage:
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . ' ';
}
In this example, the loop starts from 1 and iterates up to 5. When the value of $i is 3, the 'continue' statement is encountered and the rest of the code within the loop is skipped for that iteration. As a result, the number 3 is not echoed, and the output will be: 1 2 4 5.
Follow-up 3
Can 'break' and 'continue' be used outside of loops in PHP?
No, 'break' and 'continue' statements can only be used within loops in PHP. If you try to use them outside of a loop, you will encounter a syntax error. These statements are specifically designed to control the flow of execution within loops and are not meant to be used outside of that context.
5. Can you nest loops in PHP? If yes, how?
Yes, PHP fully supports nested loops. Each inner loop completes all its iterations for each single iteration of the outer loop.
// 2D array (matrix) traversal
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
foreach ($matrix as $row) {
foreach ($row as $cell) {
echo $cell . ' ';
}
echo "\n";
}
// Output:
// 1 2 3
// 4 5 6
// 7 8 9
Multiplication table example:
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= 5; $j++) {
echo str_pad($i * $j, 4);
}
echo "\n";
}
Performance consideration: Deeply nested loops have O(n^k) complexity where k is the nesting depth. For large datasets, consider:
- Flattening data structures before iteration
- Using database JOINs instead of nested loops over related data
- Using
array_map/array_walk_recursivefor nested array transformations
Breaking out of nested loops:
break 2; // exit two levels of loops
continue 2; // skip to next iteration of the outer loop
Follow-up 1
What is the impact on performance when nesting loops?
Nesting loops can have a significant impact on performance, especially if the loops have a large number of iterations. Each iteration of the outer loop will execute the inner loop completely. This means that the inner loop will be executed multiple times for each iteration of the outer loop, resulting in a higher number of total iterations and potentially slower execution.
Follow-up 2
Can you give an example of nested 'for' loops in PHP?
Sure! Here's an example of nested 'for' loops in PHP:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo 'Outer loop iteration: ' . $i . ', Inner loop iteration: ' . $j . '\n';
}
}
This code will output:
Outer loop iteration: 1, Inner loop iteration: 1
Outer loop iteration: 1, Inner loop iteration: 2
Outer loop iteration: 1, Inner loop iteration: 3
Outer loop iteration: 2, Inner loop iteration: 1
Outer loop iteration: 2, Inner loop iteration: 2
Outer loop iteration: 2, Inner loop iteration: 3
Outer loop iteration: 3, Inner loop iteration: 1
Outer loop iteration: 3, Inner loop iteration: 2
Outer loop iteration: 3, Inner loop iteration: 3
As you can see, the inner loop is executed completely for each iteration of the outer loop.
Follow-up 3
What happens if you use 'break' in a nested loop?
If you use the 'break' statement in a nested loop, it will only break out of the innermost loop and resume execution after the inner loop. The outer loop will continue its iterations as usual. Here's an example:
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
if ($j === 2) {
break;
}
echo 'Outer loop iteration: ' . $i . ', Inner loop iteration: ' . $j . '\n';
}
}
This code will output:
Outer loop iteration: 1, Inner loop iteration: 1
Outer loop iteration: 2, Inner loop iteration: 1
Outer loop iteration: 3, Inner loop iteration: 1
As you can see, when the inner loop reaches the second iteration, the 'break' statement is executed, breaking out of the inner loop and continuing with the next iteration of the outer loop.
Live mock interview
Mock interview: PHP Loops and Control Structures
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.