Link to home
Start Free TrialLog in
Avatar of michlcamp
michlcamp

asked on

Calculating array values - some, not all

I need to calculate values in an array the precede a value in the middle of the array:

array:
$score = array('2','2','2','3','3','3','3','3','6','9','5','9','5','10','5','5','6','7','9','12');

Open in new window


Example:

If the $_POST['score_value'] is $score[7], for example, I need to SUM the six values that come before it in the array...

$i = $_POST['score_value']
if($score[$i]) - sum all values that come before $score[$i] 

Open in new window


There are no constants - the $_POST value might be any of the array values - I can identify which one, but don't know how to SUM the values that come before it -

Thanks in advance - you guys are great!
michael
SOLUTION
Avatar of Garry Glendown
Garry Glendown
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of michlcamp
michlcamp

ASKER

Both of these solutions work perfectly - thanks! I'm gonna use the array_slice over the function, but both are valuable for the work I'm doing. Hope you don't mind I gave 50/50 points to each...

thanks again!
Thanks ... I've not used the PHP function to add up the elements or the slice function before, with them being internal functions of PHP instead of programmed code, I assume they should perform better with very large arrays ... always good to learn something new ...