Search code examples
phparraysmultidimensional-arrayuniquecounting

Get count of each unique value in one column of a 2d array


I need to count the unique values in the first column of my 2d array.

Input:

[
    ['b', 'd', 'c', 'a', ''],
    ['c', 'a', 'd', '',  ''],
    ['b', 'd', 'a', '',  ''],
    ['a', 'd', 'c', 'b', '']
]

So far, I have this code:

$count = 0;
foreach ($the_outer_array as $key=>$value) {
    if ($value [0] == 'c') {
        $count++;
    }
}

However, I can only check for one value at a time. Should I have an outer loop like foreach(range('a','d') as $i)?

Once the count is done, I am hoping to store the values in an array.

Desired result:

['b' => 2, 'c' => 1, 'a' => 1]

Solution

  • Use array_key_exists & increment the count,

    $newArray = array();
    foreach ($the_outer_array as $key=>$value) {
        $firstValue = $value[0];
        if ($foundKey = array_key_exists($firstValue,$newArray)) {
            $newArray[$firstValue] += 1;
        }
       else{
            $newArray[$firstValue] = 1;
       }
    }
    

    DEMO.