1

this is my array output:

array:2 [
  0 => array:1 [
    "medium " => " 1"
  ]
  1 => array:1 [
    " small " => " 2"
  ]
]

My solution

$sumVariant = array();
            foreach ($data as $key => $value) {
                        foreach ($value as $k => $v) {
                                    //dd(trim($v));
                            $sumVariant += trim($v);
                        }
            }
dd($sumVariant);

How can I count total for both medium and small which return 3? Thanks!!

5
  • what did you tried so far ? Commented Nov 19, 2015 at 5:31
  • 1
    Look at the array functions in the PHP manual. It should be evident after a bit of research and thought. Side note: You should maybe think about changing your handle, you may not do so well as a "d3bug3r" if you can't figure this one out on your lonesome. Commented Nov 19, 2015 at 5:36
  • @Rasclatt thanks for advice. Commented Nov 19, 2015 at 5:39
  • Spoke too late! Looks like people are going to spoon-feed you the answer. It's your lucky day! : / Commented Nov 19, 2015 at 5:39
  • Do you just want to sum up all values of your array? Commented Nov 19, 2015 at 11:25

4 Answers 4

1

I run your code as you write in your question. And have some modification like below. It gives you the correct answer.

<?php
$data =array(0=>array("medium "=>" 1"),1=>array(" small "=>" 2"));

$sumVariant=0;
foreach ($data as $key => $value) {
            foreach ($value as $k => $v) {
                        //dd(trim($v));
                $sumVariant += trim($v);
            }
}
echo $sumVariant;?>
Sign up to request clarification or add additional context in comments.

Comments

0
<?php
$total = 0;
foreach ($array as $inputArray) {
    if (array_key_exists ("medium", $array)) $total += $array["medium"] ;   
    if (array_key_exists ("small",  $array)) $total += $array["small"]  ;
}

Comments

0

Use array_walk_recurive

$array_total = 0;
$arr = array(array('small'=>2), array('medium'=>1));
array_walk_recursive($arr, function($value, $key){
    global $array_total;
 $array_total += $value;
});
    echo $array_total; // output 3

1 Comment

I have tested and it's working fine. tehplayground.com/#dgD1FwNTs (hit ctrl+enter to see output)
0
 $data =array(0=>array("medium "=>" 1"),1=>array(" small "=>" 2"));



 foreach ($data as $array_single) {
                           $sum_value += array_sum($array_single);

                }
echo $sum_value;

array_sum() return sum of integer represent as a string or int

examle::-

<?php
$a=array(' 5',15,25,'ajj');
echo array_sum($a);
?>

O/P ::- 45

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.