Search code examples
phparraysuniquecounting

PHP - Count unique in an array of objects


I have a PHP array which contains objects like this

Array
(
[0] => stdClass Object
    (
        [label] => Test 1
        [session] => 2
    )

[1] => stdClass Object
    (
        [label] => Test 2
        [session] => 2
    )

[2] => stdClass Object
    (
        [label] => Test 3
        [session] => 42
    )

[3] => stdClass Object
    (
        [label] => Test 4
        [session] => 9
    )
 )

I am trying to count the number of unique sessions within this array. I can do it when the whole thing is an array, but I am struggling to work it out when the array contains objects.

Do I need to convert the objects into arrays or is there a way of doing it with the data in its current format?


Solution

  • https://www.php.net/manual/en/function.array-column.php :

    Version    Description
    
     7.0.0     Added the ability for the input parameter to be an array of objects.
    

    Use array_column to generate new keys using the session column values. This effectively removes duplicate keys.

    Code: (Demo)

    $array = [
        (object)['label' => 'Test 1', 'session' => 2],
        (object)['label' => 'Test 2', 'session' => 2],
        (object)['label' => 'Test 3', 'session' => 42],
        (object)['label' => 'Test 4', 'session' => 9],
    ];
    echo sizeof(array_column($array, null, 'session'));
    

    Output:

    3
    

    Or in a loop:

    foreach ($array as $obj) {
        $result[$obj->session] = null;
    }
    echo sizeof($result);
    

    Both techniques avoid the extra function call of array_unique and leverage the fact that arrays cannot store duplicate keys.