fightstarr20
fightstarr20

Reputation: 12618

PHP array - count unique IDs

I have a PHP array that looks like this

Array
(
    [0] => Array
        (
            [events] => Array
                (
                    [0] => Array
                        (
                            [label] => apple
                            [id] => 3
                        )
                        [1] => Array
                        (
                            [label] => onion
                            [id] => 3
                        )
                        [2] => Array
                        (
                            [label] => pear
                            [id] => 2
                        )
                        [3] => Array
                        (
                            [label] => orange
                            [id] => 1
                        )
                        [4] => Array
                        (
                            [label] => grape
                            [id] => 41
                        )
                )
        )
)

I am trying to get a total count of unique IDs, so in the example above I would want to get a count of 4

Do I need to loop through the array or is there a function that can do it more efficiently? Currently it is a small data set but it could grow fairly large.

Upvotes: 0

Views: 54

Answers (2)

Joshua
Joshua

Reputation: 29

One way or another you'll have to loop through it. I think most efficiently would be

function getUnique($arr){
 $val = array();
  foreach($arr[0]["events"] as $v){
   $val[$v["id"]] = true;
  }
 return count($val);
}

Upvotes: 0

Barmar
Barmar

Reputation: 782285

You can use array_column to get all the IDs, and array_unique to remove the duplicates, then count that.

count(array_unique(array_column($array[0]['events'][0], 'id')))

Upvotes: 1

Related Questions