Menu
Coddy logo textTech

Recap - Iterating Over Data

Part of the Fundamentals section of Coddy's PHP journey — lesson 53 of 71.

challenge icon

Challenge

Easy

Read three lines of input:

  1. A comma-separated list of integers (e.g., 12,5,8,20,3,15,7)
  2. A minimum threshold value
  3. 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). Use continue to skip numbers outside the range. Additionally, if you encounter a number that is exactly double the maximum threshold, stop processing immediately using break.

Print two lines:

  1. The sum of valid numbers within the range
  2. 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