PHP arrays are a versatile way to store multiple values in a single variable. When paired with loops, they allow you to efficiently iterate through data, making your code cleaner and more dynamic. In this article, we’ll explore three diverse examples of using PHP arrays and loops to help you grasp these concepts easily.
This example demonstrates how to loop through an array of fruit names and print each one. It’s a simple yet effective way to understand the basics of arrays and loops in PHP.
$fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
foreach ($fruits as $fruit) {
echo "I like $fruit!\n";
}
In this snippet, we define an array called $fruits
. The foreach
loop iterates over each element, allowing us to output a message for each fruit.
Notes: You can easily modify the array to include your favorite fruits, or change the message to personalize it further.
Associative arrays allow you to use named keys to access values. This example shows how to use a loop to display a list of employees with their respective roles.
$employees = [
'Alice' => 'Manager',
'Bob' => 'Developer',
'Charlie' => 'Designer',
'Diana' => 'Tester'
];
foreach ($employees as $name => $role) {
echo "$name is a $role.\n";
}
Here, we define an associative array $employees
with names as keys and roles as values. The foreach
loop allows us to access both the key and value, printing a formatted string for each employee.
Variations: Consider adding more employees or roles, or formatting the output as an HTML list for a web page.
In this example, we’ll work with a multi-dimensional array to represent a class of students and their grades. We’ll use nested loops to print each student’s grades.
$students = [
'John' => [90, 85, 88],
'Jane' => [92, 80, 86],
'Tom' => [85, 87, 90]
];
foreach ($students as $student => $grades) {
echo "$student's grades: ";
foreach ($grades as $grade) {
echo "$grade ";
}
echo "\n";
}
In this case, $students
is a multi-dimensional array where each student has an array of grades. The outer foreach
loop iterates over each student, while the inner loop iterates through that student’s grades, allowing us to print them in a concise manner.
Notes: You can extend this example by calculating the average grade for each student or adding more students and grades to the array.