Skip to content
Distinct Values
step 1/5

Reading — step 1 of 5

Learn

~1 min readArrays

For deduplication and set-like operations, PHP gives you a few options:

$words = ["the", "quick", "brown", "the", "fox"];

// Dedupe (preserves keys; use array_values to reset)
$unique = array_unique($words);                  // ["the", "quick", "brown", "fox"]

// Use the array as a set (keys-as-set)
$set = array_flip($words);   // ["the" => 0, "quick" => 1, ...]
if (isset($set["fox"])) echo "contains fox\n";

// Counting frequencies
$counts = array_count_values($words);
// ["the" => 2, "quick" => 1, "brown" => 1, "fox" => 1]

The array_count_values builtin is a common shortcut for word counts. For a real Set type with O(1) lookups beyond what array_flip gives you, use Ds\Set from the data structures extension (pecl install ds) — but plain arrays handle nearly every case in practice.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…