Set

The Set class mimics the behavior of the JavaScript Set object in PHP. It allows you to store unique values of any type—scalars, arrays, or objects—while automatically filtering duplicates and maintaining the order in which items were added.

Concept & Generics

A Set is fundamentally different from a standard array because it enforces uniqueness. If you try to add the same value twice, the second attempt is ignored.

Type Safety

The class supports PHPDoc templates (@template T), enabling static analysis tools to enforce strict typing.

/** @var Set */
$names = new Set();

API Reference

Modification

add(T $value): void

Adds a value. If the value already exists, no action is taken.

delete(T $value): void

Removes the specified value from the collection.

clear(): void

Wipes all values from the set, resetting size to 0.

Inspection

has(T $value): bool

Checks for existence.

values(): T[]

Returns a standard indexed array of all items.

size(): int

Returns the count of items.

How Uniqueness Works

The class uses a private getKey($value) method to fingerprint values:

  • Scalars (strings/ints): Used directly as the key.
  • Objects: Fingerprinted using spl_object_id (checks instance identity).
  • Arrays: Fingerprinted using md5(serialize($value)) (checks deep equality).

Usage Examples

Basic Scalar Usage

<?php
use PP\Set;

$tags = new Set();
$tags->add('php');
$tags->add('javascript');
$tags->add('php'); // Ignored

echo $tags->size(); // Output: 2
?>

Working with Objects

<?php
use PP\Set;

$userA = new stdClass();
$userA->name = 'John';

$userB = new stdClass();
$userB->name = 'Jane';

$activeUsers = new Set();
$activeUsers->add($userA);
$activeUsers->add($userB);
$activeUsers->add($userA); // Ignored: Same instance

// However, a new object with same data is distinct:
$userC = new stdClass();
$userC->name = 'John';
$activeUsers->add($userC); // Added: Different instance ID
?>