0

In PHP, How do you sum the values of an array where the key is greater than a number (e.g., 20)?

Note: Both keys are values are numeric.

2
  • I assume the keys are not continuous? Commented Jul 5, 2011 at 20:18
  • correct, they're in order but there are keys missing Commented Jul 5, 2011 at 20:35

4 Answers 4

8
$sum = 0;

foreach ($array as $key => $value)
{
    if ($key > 20)
        $sum += $value;
}
Sign up to request clarification or add additional context in comments.

Comments

2
$sum = 0;
foreach( $array as $key => $value ){
  if( $key > 20 )
    $sum += $value;
}

Comments

0
<?php
$arr = array(...);
$n = 0;
foreach($arr as $an => $a) {
    if($an > 20) {
        $n += $a;
    }
}
echo $n;
?>

Comments

0

You can start your loop from your start key:

$sum = 0;
$keyStart = 20;
for($i = $keyStart, $c = count($array); $i < $c; $i++) {
    $sum += $arr[$i];
}

Please note that I assume that your array is numerically indexed and array keys are continuous here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.