phparraysmultidimensional-arraycounting

Count occurrences of each unique value in a column of a 2d array


So this is what I have so far:

foreach ($users as $user) {
    if (!array_keys($usersPerCity, $user->city)) {
        $usersPerCity[] = [$user->city => 1];
    } else {
        $usersPerCity[$user->city] = ($usersPerCity[$user->city] + 1);
    }
}

My +1 has no effect, and it just plainly creates city => 1 without addition.

How would I be able to increment the city that already exists?


Solution

  • You had it right in the else just do it the same way. Also, this is not what array_keys is for, did you mean array_key_exists? Anyway, just use isset and you can just increment ++:

    foreach ($users as $user) {
        if (!isset($usersPerCity[$user->city])){
            $usersPerCity[$user->city] = 1;
        } else {
            //$usersPerCity[$user->city] = ($usersPerCity[$user->city] + 1);
            $usersPerCity[$user->city]++;
        }
    }
    

    As of PHP 7.0 just extract the city from the array of objects and count the values:

    $usersPerCity = array_count_values(array_column($users, 'city'));