<?php
function createTree($array){
$tree = [];
foreach($array as $v){
$v = str_split($v);
$tmp = &$tree;
while($c = array_shift($v))
$tmp = &$tmp[strtolower($c)];
unset($tmp);
}
return $tree;
}
function findNode($value, $treeTmp){
foreach($value as $k){
if(!array_key_exists(strtolower($k), $treeTmp))
return FALSE;
else
$treeTmp = $treeTmp[$k];
}
return TRUE;
}
/* ------------ */
$data = ["round", "roundish", "word"];
$searchValue = "round";
//Normal lookU **very slow**
$result = in_array($searchValue, $data);
var_dump($result);
//Faster lookUp
$tree = createTree($data);
print_r($tree);
$result = findNode(str_split($searchValue), $tree);
var_dump($result);
//PROBLEM -> It also finds values which don't exist in '$data'
$searchValue = "ro"; //I DO NOT EXIST IN $data
$result = findNode(str_split($searchValue), $tree);
var_dump($result);
?>
- Output for 5.5.0 - 5.5.36, 5.6.0 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.7
- bool(true)
Array
(
[r] => Array
(
[o] => Array
(
[u] => Array
(
[n] => Array
(
[d] => Array
(
[i] => Array
(
[s] => Array
(
[h] =>
)
)
)
)
)
)
)
[w] => Array
(
[o] => Array
(
[r] => Array
(
[d] =>
)
)
)
)
bool(true)
bool(true)
preferences:
140.67 ms | 406 KiB | 260 Q