3
$array[0] = 100;
$array[1] = 10;
$array[2] = 15;

How can I get sum of array by its keys like key = (0,1) so the sum = 110 ?

8 Answers 8

3

Try with:

$array = array(
  0 => 100,
  1 => 10,
  2 => 15
);
$keys  = array(0, 1);
$sum   = 0;

foreach ( $keys as $key ) {
  $sum += $array[$key];
}
Sign up to request clarification or add additional context in comments.

1 Comment

@DainisAbols As far as I can see it should work as expected. What are your concerns?
3

The best and simple way is

$result = array_sum($your_array);

Comments

3
$sum = array_sum(
    array_intersect_key($array, array_flip([0,1])
);

Didn't test it, but should work :)

Comments

0
$array[0] = 100;
$array[1] = 10;


$array[2] = 15;

$sum = function($keys = array(),$arrayList= array())  {
        $s = 0;
        foreach ($arrayList as $key => $value) {
           if(in_array($key, $keys)) {
               $s+= $value;
            }
        }
        echo $s;
};
$sum(array(0,1),$array);

1 Comment

Just curious: Why do you use an anonymous function here? As far as I can see you can completely omit it, rename some variable names ($container (bad name anyway ;)) => $array to iterate over and $key must be set) and at the end simply echo $s.
0

Try this

$array[0] = 100;
$array[1] = 10;
$array[2] = 15;

echo array_sum($array);

OR try this

$array[0] = 100;
$array[1] = 10;
$array[2] = 15;
$sum=0;
foreach (range(0,1) as $key)
{
    $sum = $sum+$array[$key];
}
echo $sum;

Comments

0

Here is my solution to sum Arrays by defined keys:

$myArray=Array("Array Title","1000",2000,3000}; // array example with stings and integers

var_dump(array_intersect_key($myArray, array_flip(Array(1,2)))); // int(3000)
var_dump($myArray); // int(6000)

References:

array_intersect_key

array_flip

Comments

-1

if you want to sum intial two keys then use below code:

array_sum(array_slice($array,0,2)); // will return 110

References:

array_sum

array_slice

Comments

-2
$count = 0;
for($i=0;$i<count($array);$i++){
 $count = $count + $array[$i];
}

echo $count;

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.