Click here to Skip to main content
15,896,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
PHP


Task: Create a function "addAll()" that will take an array as input parameter.
The function will sum all the elements in the array and then remove the first element of the array.
The function should repeat this until the array is empty and then return the total.
For example: For the array [1,1,1,1,1], the result should be 15 -> 5+4+3+2+1=15


What I have tried:

<?php 
function addAll($Array) {
    $total = 0;
    foreach ($Array as $value) {
        $total += $value;
         }
    return $total;
}

//$remove = array_shift($sumArray); 

/** Given array **/
$sumArray = array(1,1,1,1,1); 
/** Calling function **/
$myAnswer = addAll($sumArray);

/** My result **/
 echo "The result is : " , $myAnswer; // result = 5 

 ?>
Posted
Updated 3-May-21 20:34pm
Comments
Patrice T 3-May-21 15:57pm    
And you have a question ?

A little mathematics goes a long way in programming. In the 5 element case, what you're adding is:

(a + b + c + d + e) + (b + c + d + e) + (c + d + e) + (d + e) + e

That's the same as summing 1 + 2b + 3c + 4d + 5e. It's not hard to see that you can get your answer by adding 1*$Array[0] + 2*%Array[1] + 3*$Array[2] + ... + n*$Array[n-1], where n is the length of the array. So you can write a loop that computes this in just one pass through the data, with a variable $k that varies from 0 to n-1 and summing (k+1)*$Array[$k] on each iteration.

Play with that idea and see if you can't come up with a very simple solution in code.
 
Share this answer
 
Comments
Johan Kok 2021 5-May-21 4:49am    
Many thanks for this new perspective to handle a possible solution differently. I appreciated it sincerely.
You need to add a loop and a total to where you call addAll.
Inside the loop, call the function, and add the result into your total. Then remove either the first or the last item. If the array is empty, exit the loop. if it isn't, go around again.
After the loop, print your total.

But this is clearly homework, so I'll give you no code!
 
Share this answer
 
Comments
Johan Kok 2021 5-May-21 4:50am    
Many thanks for advice supplied --- will definitely make use of it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900