0

I need to get a tally of different statues in a dataset. I expected this would be simple, I create a $statuses array, loop through the data and increment a count for each status in my $statuses. Here is what I've done:

$data = array(
    array('status'=>'a'),
    array('status'=>'b'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'c'),
    array('status'=>'b'),
    array('status'=>'b'),
    array('status'=>'a'),
    array('status'=>'a'),
    array('status'=>'a'),
);

$statuses = array();
foreach($data as $row) {
    if(!in_array($row['status'], $statuses)) {                                           
        $statuses[$row['status']] = 0;
    }
    $statuses[$row['status']] += 1;
}

var_dump($statuses);

Results in:

array(3) { ["a"]=> int(1) ["b"]=> int(1) ["c"]=> int(1) }

I can think of a few other ways to accomplish this, but I'm too curious: why aren't my statuses incrementing here? I've also tried a few other methods of incrementing, but it does not matter:

$statuses[$row['status']]++;
++$statuses[$row['status']];
$statuses[$row['status']] = $statuses[$row['status']] + 1;

It's all the same.

I struggled to search for similar questions to this, most of the results I found are "how do I loop" or otherwise irrelevant. Any help with the title would also be appreciated.

3
  • 2
    it's the in_array($row['status'], $statuses) that doesn't do what you expect. Commented Jan 6, 2018 at 23:36
  • 1
    change that to !isset($statuses[$row['status']]) and it'll work! 3v4l.org/MLUgK Commented Jan 6, 2018 at 23:37
  • @Jeff Thanks for the help! I knew I must have been overlooking something, that seems so obvious now. Commented Jan 7, 2018 at 0:01

2 Answers 2

3

You can use some built-in functions for that:

$result = array_count_values(array_column($data, 'status'));

NB: in_array will look for values, not keys. The function to look for keys is array_key_exists

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

1 Comment

Thank you! I was scratching my head, but that makes a lot more sense. I read Jeff and your answers at once, I'm going to accept his answer but it was a difficult choice. No offense, I appreciate the help!
1

It's the in_array($row['status'], $statuses) that doesn't do what you expect (because it searches for values - see @trincot's answer). You could change the condition to

if(!isset($statuses[$row['status']])) { 
    $statuses[$row['status']] = 0;
}

and you'll get your desired result:

array(3) {
  ["a"]=>int(4)
  ["b"]=>int(3)
  ["c"]=>int(7)
}

Fiddle: https://3v4l.org/MLUgK

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.