Calculating array values - some, not all

I need to calculate values in an array the precede a value in the middle of the 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


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!
Who is Participating?
lwadwellConnect With a Mentor Commented:
what about ...
$score = array('2','2','2','3','3','3','3','3','6','9','5','9','5','10','5','5','6','7','9','12');

$i = $_POST['score_value'];
if ($score[$i] ) $total = array_sum(array_slice($score, 0, $i-1));

echo $total;

Open in new window

You may want to take a copy of $score and slice it if you need it for other things.
Garry GlendownConnect With a Mentor Consulting and Network/Security SpecialistCommented:
Here's a quick hack ...
$score = array('2','2','2','3','3','3','3','3','6','9','5','9','5','10','5','5','6','7','9','12');

function mysum($pos,$offset=0)
global $score;

        foreach ($score as $idx => $val) {
                if ($idx+$offset==$pos) return($sum);

print "With 1st array position as #0:\n";
print "The sum before position 7 is ".mysum(7) ."\n";
print "The sum before position 12 is ".mysum(12) ."\n";

print "With 1st array position as #1:\n";
print "The sum before position 7 is ".mysum(7,1) ."\n";
print "The sum before position 12 is ".mysum(12,1) ."\n";


Open in new window

Just drop the function into your code and you should be good to go ... depending on whether you want the first array position seen as "0" or "1", use the second argument (or alter the default)
michlcampAuthor Commented:
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!
Garry GlendownConsulting and Network/Security SpecialistCommented:
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 ...
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.