PHP Function to find Array Sums

Links for php scripts

Moderators: egami, macek, gesf

Post Reply
jinsonkv
New php-forum User
New php-forum User
Posts: 1
Joined: Wed Sep 29, 2021 11:57 pm

Thu Sep 30, 2021 12:00 am

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
simonbrahan
php-forum Super User
php-forum Super User
Posts: 153
Joined: Mon Jun 08, 2020 2:00 am
Contact:

Thu Sep 30, 2021 5:35 am

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: Select all

/**
 * 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;
}
Post Reply