Recap - Iterating Over Data
Part of the Fundamentals section of Coddy's PHP journey. Lesson 53 of 71.
Challenge
EasyRead three lines of input:
- A comma-separated list of integers (e.g.,
12,5,8,20,3,15,7) - A minimum threshold value
- A maximum threshold value
Process the array to find the sum of all numbers that fall within the range (inclusive of both minimum and maximum). First check if a number is exactly double the maximum threshold and, if so, stop immediately with break. Otherwise, use continue to skip numbers outside the range.
The first line is read with explode, so $numbers holds strings while $min and $max are integers. Convert each element with intval() (or a (int) cast) before you compare it with the thresholds or add it to the sum.
Print two lines:
- The sum of valid numbers within the range
- The count of numbers that were added to the sum
Example 1:
If the inputs are 5,12,8,20,15,3,10, 5, and 15, the output should be:
50
5(5 + 12 + 8 + 15 + 10 = 50, five numbers are within range 5-15)
Example 2:
If the inputs are 2,8,12,20,6,14, 5, and 10, the output should be:
8
1(Processing stops at 20 because it's double the max of 10; only 8 was added before that point, so the sum is 8 and the count is 1)
Example 3:
If the inputs are 1,2,3,4,5, 10, and 20, the output should be:
0
0(No numbers fall within the range 10-20)
Try it yourself
<?php
// Read input
$numbers = explode(',', trim(fgets(STDIN)));
$min = intval(trim(fgets(STDIN)));
$max = intval(trim(fgets(STDIN)));
// Initialize variables
$sum = 0;
$count = 0;
// TODO: Write your code here
// Loop through the numbers array
// Use 'continue' to skip numbers outside the range (min to max inclusive)
// Use 'break' if you encounter a number exactly double the maximum threshold
// Keep track of the sum and count of valid numbers
// Output the results
echo $sum . "\n";
echo $count;
?>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 Decisions8Loops
For LoopWhile LoopForeach LoopLooping with Keys and ValuesBreak StatementContinue StatementRecap - Iterating Over Data3Basic Operators
Arithmetic OperatorsModulo OperatorExponentiation OperatorCombined AssignmentIncrement/DecrementOperator PrecedenceRecap - Simple CalculationsString OperatorsPractice on your own: Online PHP compiler