Jump to content

Recommended Posts

Hi, I am looking to sort this array function in PHP.

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

Link to comment
https://forums.phpfreaks.com/topic/313841-function-to-find-sum-of-an-array/
Share on other sites

2 hours ago, jameskv said:

Hi, I am looking to sort this array function in PHP.

I assume you are not using "sort" in it's technical sense here. 

There is no sorting required in any part of this, which looks like a Homework Assignment, to me (so you don't get the answer straight away! 😀). 

 

2 hours ago, jameskv said:

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.

As an aside, I would say that this function should take three parameters, not two. 

1. The array itself, 
2. the lower limit of values you want to look for, 
3. The upper limit of values you want to look for. 

Anyway ...
Within the function, you'll need a local variable in which to store the calculated total.  Remember to start this off at zero. 

Then, loop through the elements of the array and compare each element to the lower and upper limits (parameters).  If the element value is greater than or equal to the lower limit and less than or equal to the upper limit, then add the element value to the total. 

After the loop, return the total. 

Regards, 
   Phill  W.

 

 

In my experience, between is usually inclusive EG

mysql> select id, prod_name
    -> from products
    -> where id between 2 and 4;
+----+-----------+
| id | prod_name |
+----+-----------+
|  2 | Bbb       |
|  3 | Ccc       |
|  4 | Ddd       |
+----+-----------+

and the example given by the OP certainly implies that is the case here too.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.