A zero-dependency prefix tree (Trie) library for HolyPHP supporting fast word insertion, lookup, deletion with node pruning, prefix checking, lexicographically sorted autocomplete, and word counting.
bundled — works offlinezero dependenciesprefixautocomplete
trie_create(): Trie — Creates and returns a new empty Trie.
trie_from_array(array $words): Trie — Creates a Trie populated with all strings in $words. Throws if any element is not a string or is empty.
Trie Class
new Trie() — Constructs an empty prefix tree.
insert(string $word): void — Inserts $word into the trie. Inserting an existing word is a no-op (word count is unchanged). Throws if $word is empty.
search(string $word): bool — Returns true if $word exists in the trie, false otherwise.
has(string $word): bool — Alias for search($word).
startsWith(string $prefix): bool — Returns true if at least one word in the trie starts with $prefix. For an empty prefix, returns true iff the trie is non-empty.
delete(string $word): bool — Removes $word from the trie and prunes unused nodes. Returns true if the word was found and removed, false otherwise. Throws if $word is empty.
autocomplete(string $prefix, int $limit = 10): array — Returns up to $limit words starting with $prefix in lexicographical order. Throws if $limit < 0.
words(): array — Returns all words stored in the trie in lexicographical order.
count(): int — Returns the number of distinct words in the trie.
isEmpty(): bool — Returns true if the trie contains no words.
clear(): void — Removes all words from the trie.
Error Handling
Invalid arguments throw an Exception with a clear trie: ... message:
insert("") -> Exception("trie: word must not be empty")
delete("") -> Exception("trie: word must not be empty")
autocomplete("a", -1) -> Exception("trie: limit must be non-negative, got -1")
trie_from_array([123]) -> Exception("trie: all elements in words array must be strings")
Examples
01Quick start
Bundled with the compiler — import "trie"; works offline in any file, or add it to a project with hphp install trie.