0

I am trying to get the count of key data and sum them up and show. I need to count all the key data in a php array and show the output as below i tried but was not able to get all the array count.

Output:
 chromi: 7
 detruch: 6
 detroy: 4

Find the array picture below, this is how i am getting array data enter image description here

4
  • you want to count how many element in the array ? Commented Apr 3, 2019 at 10:36
  • s i need to sum them up and show, above i hv given output Commented Apr 3, 2019 at 10:37
  • Don't post images of text. Use json or var_export instead Commented Apr 3, 2019 at 10:53
  • sure here after ill try to follow that Commented Apr 3, 2019 at 10:55

3 Answers 3

2

Better way will be to get array of values and use array-count-values:

$array = [
        ['someKey' => 'Value 1'],
        ['someKey1' => 'Value 1'],
        ['someKey2' => 'Value 2'],
        ['someKey3' => 'Value 3'],
    ];

$arr = array_map(function ($e) {return reset($e);},$array);
print_r(array_count_values($arr));

Output will be:

Array
(
    [Value 1] => 2
    [Value 2] => 1
    [Value 3] => 1
)

I just improve @Qirel answer. This version can support multi-value to count. Live demo: 3v4l

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks it works but could u explain me how it works.
Sure - first I took the actual value you want to count (using the array_map) - in your case chromi. Afterward I use build-in PHP function to count them
1

Loop the array, pick the first value using reset(), and count that index of the $result array.

$array = [
        ['someKey' => 'Value 1'],
        ['someKey1' => 'Value 1'],
        ['someKey2' => 'Value 2'],
        ['someKey3' => 'Value 3'],
    ];

$result = [];

foreach ($array as $v) {
    $value = reset($v);
    if (!isset($result[$value]))
        $result[$value] = 0;

    $result[$value] += 1;
}
print_r($result);

Comments

0

First flip thekey with value and then loop the array to incrment the counters :

Try this snippet :

$chromi = 0 ;
$detruch = 0 ;
$detroy = 0;
$data = array_flip($data);
foreach($data as $key=>$value){
      if($key=='chromi'){
        $chromi++;
      }
      else if ($key=='chromi'){
      $chromi++
       }
        else if ($key=='detroy'){
      $detroy++
       }
}

1 Comment

actually the key also comes dynamically from DB, so we cant do like the above, Each user has his own type of editing option (i mean the key values), So for some user it may be different and goes n number

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.