d3bug3r
d3bug3r

Reputation: 2586

Php array count total value from key value pair

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!!

Upvotes: 1

Views: 1224

Answers (4)

Santosh Patel
Santosh Patel

Reputation: 539

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;?>

Upvotes: 1

Parth Chavda
Parth Chavda

Reputation: 1829

 $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

Upvotes: 0

Karan
Karan

Reputation: 2112

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

Upvotes: 0

Halayem Anis
Halayem Anis

Reputation: 7785

<?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"]  ;
}

Upvotes: 0

Related Questions