Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to display array values with do while or for statement in my PHP?
In PHP, you can display array values using loop structures like do-while and for statements. These loops provide different approaches to iterate through array elements and display them.
Syntax
The basic syntax for a do-while loop is −
do {
// statements
} while (condition);
The basic syntax for a for loop is −
for (initialization; condition; increment) {
// statements
}
Using do-while Loop
The do-while loop executes the code block at least once before checking the condition ?
<?php
$values = array('John', 'David', 'Mike', 'Sam', 'Carol');
$i = 0;
$len = count($values);
do {
echo $values[$i] . " ";
$i++;
} while ($i < $len);
?>
John David Mike Sam Carol
Using for Loop
The for loop is more concise and commonly used for array iteration ?
<?php
$values = array('John', 'David', 'Mike', 'Sam', 'Carol');
$len = count($values);
for ($i = 0; $i < $len; $i++) {
echo $values[$i] . " ";
}
?>
John David Mike Sam Carol
Comparison
| Loop Type | Minimum Executions | Best Use Case |
|---|---|---|
| do-while | 1 (executes at least once) | When you need to run code before checking condition |
| for | 0 (may not execute if condition is false) | When you know the number of iterations in advance |
Conclusion
Both do-while and for loops can effectively display array values in PHP. The for loop is generally preferred for array iteration due to its concise syntax, while do-while is useful when you need guaranteed execution.
Advertisements
