Introduction
In PHP, array traversal means accessing and processing array elements one by one using loops. It helps you display records, calculate totals, search for values, and manage lists of data efficiently. In this chapter, you will practise Array Traversal and Looping in PHP using foreach, for, while, and nested loops through practical solved PHP questions.
Question 1: Display All Array Elements Using Foreach
Problem Statement
Create an array containing five employee names and display each name using a foreach loop.
PHP Solution
<?php
$employees = ["Rahul", "Priya", "Amit", "Neha", "Karan"];
foreach ($employees as $employee) {
echo $employee . "\n";
}
?>
Sample Output
Rahul
Priya
Amit
Neha
Karan
Explanation
The foreach loop accesses each element of the $employees array one by one. The current element is stored in the $employee variable and displayed using echo.
Concepts Covered
- Array traversal
foreachloop- Accessing array elements
Question 2: Display Array Elements with Their Indexes
Problem Statement
Create an array of programming languages and display each language along with its index.
PHP Solution
<?php
$languages = ["PHP", "Python", "Java", "JavaScript"];
foreach ($languages as $index => $language) {
echo "Index " . $index . ": " . $language . "\n";
}
?>
Sample Output
Index 0: PHP
Index 1: Python
Index 2: Java
Index 3: JavaScript
Explanation
The foreach loop uses two variables: $index stores the array index, while $language stores the corresponding value. This is useful when you need both the position and value of an element.
Concepts Covered
foreachwith key and value- Array indexes
- Accessing array keys
Question 3: Traverse an Array Using a For Loop
Problem Statement
Create an array of five product prices and display every price using a for loop.
PHP Solution
<?php
$prices = [500, 750, 1200, 900, 1500];
for ($i = 0; $i < count($prices); $i++) {
echo $prices[$i] . "\n";
}
?>
Sample Output
500
750
1200
900
1500
Explanation
The for loop starts with index 0 and continues while $i is smaller than the array length. The expression $prices[$i] accesses the element at the current index.
Concepts Covered
forloopcount()function- Array index access
Question 4: Calculate the Total of Array Elements
Problem Statement
Create an array containing five daily sales amounts and calculate their total using a foreach loop.
PHP Solution
<?php
$sales = [2500, 3000, 1800, 4200, 3500];
$total = 0;
foreach ($sales as $amount) {
$total = $total + $amount;
}
echo "Total Sales: Rs. " . $total;
?>
Sample Output
Total Sales: Rs. 15000
Explanation
The $total variable starts at 0. During each loop iteration, the current sales amount is added to $total. After the loop finishes, the variable contains the total of all sales.
Concepts Covered
- Array traversal
foreachloop- Running total
- Addition operator
Question 5: Traverse an Array Using a While Loop
Problem Statement
Create an array of five student names and display all names using a while loop.
PHP Solution
<?php
$students = ["Ankit", "Riya", "Mohit", "Simran", "Vikas"];
$i = 0;
while ($i < count($students)) {
echo $students[$i] . "\n";
$i++;
}
?>
Sample Output
Ankit
Riya
Mohit
Simran
Vikas
Explanation
The $i variable starts at index 0. The while loop continues as long as $i is smaller than the number of students. After displaying each name, $i++ moves to the next index.
Concepts Covered
whileloop- Array index access
- Increment operator
count()function
Question 6: Traverse an Associative Array Using Foreach
Problem Statement
Create an associative array containing employee names and their salaries. Display each employee’s name and salary.
PHP Solution
<?php
$employees = [
"Rahul" => 25000,
"Priya" => 32000,
"Amit" => 28000,
"Neha" => 35000
];
foreach ($employees as $name => $salary) {
echo "Employee: " . $name;
echo " | Salary: Rs. " . $salary . "\n";
}
?>
Sample Output
Employee: Rahul | Salary: Rs. 25000
Employee: Priya | Salary: Rs. 32000
Employee: Amit | Salary: Rs. 28000
Employee: Neha | Salary: Rs. 35000
Explanation
The foreach loop accesses each associative array entry. The $name variable stores the key, and $salary stores its corresponding value.
Concepts Covered
- Associative arrays
foreachloop- Key-value traversal
Question 7: Traverse a Multidimensional Array Using Nested Foreach
Problem Statement
Create a multidimensional array containing student names and their subject marks. Display each student’s marks using nested foreach loops.
PHP Solution
<?php
$students = [
"Rahul" => [
"PHP" => 85,
"Python" => 90
],
"Priya" => [
"PHP" => 92,
"Python" => 88
]
];
foreach ($students as $name => $subjects) {
echo "Student: " . $name . "\n";
foreach ($subjects as $subject => $marks) {
echo $subject . ": " . $marks . "\n";
}
echo "\n";
}
?>
Sample Output
Student: Rahul
PHP: 85
Python: 90
Student: Priya
PHP: 92
Python: 88
Explanation
The outer foreach loop accesses each student. The inner foreach loop accesses the subjects and marks stored inside that student’s array. This approach is useful for processing structured records.
Concepts Covered
- Multidimensional arrays
- Nested
foreachloops - Associative array traversal
Question 8: Find the Highest Number in an Array Using a Loop
Problem Statement
Create an array of product prices and find the highest price using a foreach loop.
PHP Solution
<?php
$prices = [450, 1200, 750, 1800, 950];
$highest = $prices[0];
foreach ($prices as $price) {
if ($price > $highest) {
$highest = $price;
}
}
echo "Highest Price: Rs. " . $highest;
?>
Sample Output
Highest Price: Rs. 1800
Explanation
The $highest variable initially stores the first price. The loop compares every price with the current highest value. Whenever a larger price is found, $highest is updated.
Concepts Covered
foreachloop- Conditional statement
- Array traversal
- Finding the maximum value
Question 9: Search for an Employee in an Array Using a Loop
Problem Statement
Create an array of employee names and search for the employee named “Neha”. Display whether the employee is found.
PHP Solution
<?php
$employees = ["Rahul", "Amit", "Neha", "Priya", "Karan"];
$searchName = "Neha";
$found = false;
foreach ($employees as $employee) {
if ($employee == $searchName) {
$found = true;
break;
}
}
if ($found) {
echo $searchName . " is found in the employee list.";
} else {
echo $searchName . " is not found in the employee list.";
}
?>
Sample Output
Neha is found in the employee list.
Explanation
The loop checks each employee name against $searchName. If a match is found, $found becomes true, and break stops the loop immediately. The final if-else statement displays the search result.
Concepts Covered
- Array searching
foreachloopif-elsestatementbreakstatement- Boolean variables
Question 10: Count How Many Times a Value Appears in an Array
Problem Statement
Create an array containing product categories and count how many times the category “Electronics” appears using a foreach loop.
PHP Solution
<?php
$categories = [
"Electronics",
"Clothing",
"Electronics",
"Furniture",
"Electronics",
"Clothing"
];
$searchCategory = "Electronics";
$count = 0;
foreach ($categories as $category) {
if ($category == $searchCategory) {
$count++;
}
}
echo $searchCategory . " appears " . $count . " times.";
?>
Sample Output
Electronics appears 3 times.
Explanation
The $count variable starts at 0. The loop checks every category. Whenever it finds “Electronics”, the counter increases by one. After the loop finishes, $count contains the total number of matching elements.
Concepts Covered
- Array traversal
foreachloop- Conditional checking
- Counter variable
- Increment operator
Key Takeaways
- Array traversal means accessing array elements one by one.
- Use
foreachwhen you want to process array values easily. - Use
forandwhileloops when you need index-based traversal. - Use
$key => $valuewithforeachto access associative array keys and values. - Use nested
foreachloops to process multidimensional arrays. - Use loops to calculate totals, search records, find maximum values, and count matching elements.
- The
breakstatement stops a loop when the required condition is met.
Frequently Asked Questions (FAQs)
1. What is array traversal in PHP?
Array traversal is the process of accessing and processing array elements one by one using loops.
2. Which loop is commonly used for array traversal in PHP?
The foreach loop is commonly used because it directly accesses array elements without requiring manual index management.
3. Can we use a for loop to traverse an array?
Yes. A for loop can traverse an indexed array using its indexes and the count() function.
4. What is the difference between for and foreach loops?
A for loop usually uses an index to access elements, while a foreach loop directly accesses each array element.
5. Can we traverse an associative array using foreach?
Yes. Use foreach ($array as $key => $value) to access both keys and values.
6. How can we traverse a multidimensional array in PHP?
Use nested loops, such as a foreach loop inside another foreach loop, to access nested array elements.
7. Can we use a while loop to traverse an array?
Yes. Start with index 0, check the array length in the while condition, and increment the index after each iteration.
8. What does break do inside an array traversal loop?
The break statement immediately stops the loop. It is useful when you find the required element and do not need to continue searching.
9. How can we calculate the total of array values using a loop?
Create a total variable initialized to 0 and add each array element to it during loop execution.
10. Why is array traversal important in PHP?
Array traversal makes it easier to process lists of records, display information, calculate results, search data, and work with structured information.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
