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.
in_array($row['status'], $statuses)that doesn't do what you expect.!isset($statuses[$row['status']])and it'll work! 3v4l.org/MLUgK