Foreach Loop
Part of the Fundamentals section of Coddy's PHP journey — lesson 49 of 71.
When working with arrays, you often need to go through each element one by one. While you could use a for loop with an index counter, PHP provides a cleaner solution: the foreach loop.
The foreach loop is designed specifically for iterating over arrays. It automatically handles the counting and gives you direct access to each element.
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>This outputs:
apple
banana
cherryThe syntax is straightforward: foreach ($array as $item). On each iteration, the next element from the array is assigned to $item, and you can use it inside the loop body.
Compare this to achieving the same result with a for loop:
<?php
$fruits = ["apple", "banana", "cherry"];
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "\n";
}
?>The foreach version is shorter and easier to read. You don't need to manage an index variable or worry about the array's length—PHP handles all of that for you.
Challenge
EasyRead a single line of input containing a comma-separated list of numbers (e.g., 10,25,5,30,15).
Use a foreach loop to iterate through the array and calculate the sum of all numbers. Print the total sum.
Example 1:
If the input is 10,25,5,30,15, the output should be:
85Example 2:
If the input is 1,2,3,4,5, the output should be:
15Example 3:
If the input is 100,200,300, the output should be:
600Cheat sheet
The foreach loop is designed specifically for iterating over arrays without managing index variables.
Basic syntax:
<?php
foreach ($array as $item) {
// use $item
}
?>Example:
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
?>This is cleaner than using a for loop with an index counter, as PHP automatically handles the counting and array length.
Try it yourself
<?php
// Read input
$input = trim(fgets(STDIN));
$numbers = explode(',', $input);
// TODO: Write your code below to calculate the sum using a foreach loop
$sum = 0;
// Output the result
echo $sum;
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Comparison & Logical Operators
Comparison OperatorsEquality & IdentityLogical Operators Part 1Logical Operators Part 2Recap - Simple Logic2Variables and Data Types
NumbersStrings and QuotesBooleansNaming ConventionsRecap - Variable InitEmpty VariablesString ConcatenationGetting User InputCast to Different Types5Conditional Logic
If StatementIf - ElseThe Ternary OperatorNull Coalescing OperatorSwitch StatementRecap - Making Decisions3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString Operators