Here is sometime I do a lot in PHP. Searching for a needle in a haystack.
$names = [
'Mike',
'John',
'Dave',
'Tony'
];
$gotDave = in_array('Dave', $names);
The runtime of in_array is O(n) where n is the number of elements.
I often setup my lookup data structure to look like this.
$names = [
'Mike' => true,
'John' => true,
'Dave' => true,
'Tony' => true
];
$gotDave = isset($names['Dave']);
The runtime is O(1) because in php the associative array is a hashmap.
Some questions:
- should I do this? is this good practice?
- is there a better value for the right hand ride