Skip to content

Core\ObjectSet::count

$objectSet->count(): uint

Returns how many values a Core\ObjectSet has, as a uint. An empty set has a count of 0. This replaces count($storage) on an SplObjectStorage.

Each value is in a set once, so the count is the number of distinct values. Adding a value that is already in the set does not change the count. Two objects with equal property values are two values, and they count as two.

count does not change the set. To check only if the set is empty, isEmpty is shorter.

The examples show the count after adding and removing, the number of distinct values in a list, and a common use: a limit on how many different guests can join an event.

Return value

Returns uint. The number of values in the set. An empty set gives 0.

Examples

Count after add and remove

<?nvs
// Shows how the count of a set changes when you add and remove values.
final class File
{
public string $path;
public function constructor(string $path)
{
$this->path = $path;
}
}
File $readme = new File('README.md');
File $notes = new File('notes.txt');
Core\ObjectSet<File> $open = new Core\ObjectSet<File>();
// A new set is empty. This prints 0.
echo $open->count(), "\n";
$open->add($readme);
$open->add($notes);
// This prints 2.
echo $open->count(), "\n";
$open->remove($readme);
// This prints 1.
echo $open->count(), "\n";
Output
0
2
1

Count distinct values

<?nvs
// Shows how to count the different values in a list.
array<string> $tags = ['news', 'sport', 'news', 'music', 'sport', 'news'];
Core\ObjectSet<string> $distinct = new Core\ObjectSet<string>();
foreach ($tags as string $tag) {
$distinct->add($tag);
}
// The list has 6 entries. This prints 6.
echo Core\Arr::count($tags), "\n";
// Equal strings are one value, so the set has 3. This prints 3.
echo $distinct->count(), "\n";
Output
6
3

Limit guests at an event

<?nvs
// Shows how to limit how many different guests can join an event.
final class Guest
{
public string $name;
public function constructor(string $name)
{
$this->name = $name;
}
}
final class Event
{
public uint $seats;
public Core\ObjectSet<Guest> $guests;
public function constructor(uint $seats)
{
$this->seats = $seats;
$this->guests = new Core\ObjectSet<Guest>();
}
public function join(Guest $guest): bool
{
// A guest who has already joined does not take a second seat.
if ($this->guests->has($guest)) {
return true;
}
if ($this->guests->count() >= $this->seats) {
return false;
}
$this->guests->add($guest);
return true;
}
}
Guest $ana = new Guest('Ana');
Guest $li = new Guest('Li');
Guest $sam = new Guest('Sam');
array<Guest> $arrivals = [$ana, $li, $ana, $sam];
Event $talk = new Event(2);
// This prints "Ana yes", "Li yes", "Ana yes" and "Sam no".
foreach ($arrivals as Guest $guest) {
echo $guest->name, ' ', $talk->join($guest) ? 'yes' : 'no', "\n";
}
// This prints 2.
echo $talk->guests->count(), "\n";
Output
Ana yes
Li yes
Ana yes
Sam no
2