<?php
class Trie {
public $data = [];
public $value = false;
}
$tokens = [
"apple" => "T_APPLE",
"ape" => "T_APE",
"cape" => "T_CAPE",
];
$root = new Trie;
foreach ($tokens as $name => $value) {
$node = $root;
// For each character in the string
for ($i = 0; $i < strlen($name); $i++) {
$char = $name[$i];
if (!isset($node->data[$char])) {
// If we don't have a child with that char
// Create it
$node->data[$char] = new Trie;
}
// Reset the node for the next character
$node = $node->data[$char];
}
// Finally, set the value on the final node
$node->value = $value;
}
// "ape" is a valid token, so we expect T_APE
var_dump($root->data['a']->data['p']->data['n']->value); // T_APE