PHP Function to find Array Sums

A

Anonymous

Guest
Hi,
I am looking for an answer for a function.
Question: Given an array A = [10,20,30,40,50,60,70,80,90,100], write a function that receives two integers as parameters. The function returns the sum of elements in the array found between those two integers.

For example, if we use 20 and 50 as parameters, the function should return 140.

Can anybody help me to sort this out?
Thanks
 
This will do it. You should have a think about what to do if your inputs are unexpected; if your $nums isn't just integers or is out of order, for example.

Code:
/**
 * Assumes $nums is an ordered array of integers containing $start and $end
 * and that $start is less than $end
 */
function sumOfRange(array $nums, int $start, int $end): int
{
    // Get the array index of our first number to add
    $start_index = array_search($start, $nums);
    // Get the array index of our last number to add
    $end_index = array_search($end, $nums);

    $out = 0;

   // For each array index between our two numbers, add that array value to the output
    for ($index = $start_index; $index <= $end_index; $index++) {
        $out += $nums[$index];
    }

    return $out;
}
 
Back
Top