Skip to content
Advertisement

Counting entries in sub/subarray

I am working on a chat. I have an array that contains the info regarding the room (in the example below, 2 rooms (the lounge, the beach)).

I have an issue when I have an empty room (in the example the beach), as it contains by default no user, (which is a Null user).

$roomNusers=Array ( 
  [The Lounge] => 
        Array ( [id] => 1 
                [privacy] => public 
                [users] => Array 
                   [QUICHE POIREAU] => Array
                       [smiley] => smi_smile.gif
                       [name] => QUICHE POIREAU 
                       [state] => NULL
                       [id] => 1 ) 
                   [JOHN DOE] => Array
                       [smiley] => smi_smile.gif 
                       [name] => Joe FRANC 
                       [state] => 
                       [id] => 40 )
   [The Beach] => Array
      [id] => 2 
      [privacy] => public 
      [users] => Array 
           [Null] => Array 
                 [smiley] => Null
                 [name] => Null
                 [state] => Null
                 [id] => Null

I am trying to count, in my array, the number of users currently present in the room. Looking around Stack Overflow, I managed to find the solution I wanted:

foreach($roomNusers as $room => $value)
    {
      echo $room.' user count:'.count($room['users'])
    }

This output:

The lounge user count: 2
The beach user count: 1

My issue is that it counts the user [null] in the beach.

How can I count the number of users not null per room?

I thought of a workaround with something similar to:

$countperroom= .count($room['users'])-1;
if(isset(end([$room]['users']))){$countuser+1;}

In this, the last user is empty, I do not add an user, but I do not know how to write this.

Advertisement

Answer

Rather than counting the number of values in $room['users'], you could count the number of keys after filtering them to remove empty keys:

foreach ($rooms as $name => $room) {
    $users = count(array_filter(array_keys($room['users'])));
    echo "$name: $users usersn";
}

Output (for your sample data):

The Lounge: 2 users
The Beach: 0 users

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement