3v4l.org

run code in 300+ PHP versions simultaneously
<?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
Output for 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
Warning: Undefined array key "n" in /in/b7eDb on line 32 Warning: Attempt to read property "value" on null in /in/b7eDb on line 32 NULL
Output for 7.2.0 - 7.2.33, 7.3.0 - 7.3.31, 7.4.0 - 7.4.33
Notice: Undefined index: n in /in/b7eDb on line 32 Notice: Trying to get property 'value' of non-object in /in/b7eDb on line 32 NULL
Output for 7.3.32 - 7.3.33
NULL
Output for 5.4.2 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.25
Notice: Undefined index: n in /in/b7eDb on line 32 Notice: Trying to get property of non-object in /in/b7eDb on line 32 NULL

preferences:
180.25 ms | 402 KiB | 244 Q