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).

JavaScript

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:

JavaScript

This output:

JavaScript

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:

JavaScript

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:

JavaScript

Output (for your sample data):

JavaScript

Demo on 3v4l.org

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