I wrote a simple function that checks if a given string contains a predefined sub-string with stripos() and returns the key of the sub string. Actually I need the key string to use it in other parts of the script.
I’m wondering if there is a better way of doing this since currently I’m parsing the entire array and it returns the result when the match is found. So if the array gets bigger, it gets slower.
$needles = array(
'a' => 'ab',
'b' => 'bc',
'c' => 'cd',
'd' => 'de',
'e' => 'ef'
);
echo get_key('cd', $needles) . '<br />';
echo get_key('my_de_string', $needles) . '<br />';
echo get_key('e_ab', $needles) . '<br />';
function get_key($mystring, $needles) {
foreach ($needles as $key => $needle)
{
if ((stripos($mystring, $needle)) !== false)
{
return $key;
}
}
}
Sorry if this kind of question has been asked before. Thanks for your information.
You are not parsing the entire array, you are only parsing the entities the foreach loops through. I am almost certain that this is the fastest way to do this.
If you want to make it faster, depending on how many times you need to run this, and how big your array is goin to become, a trie structure would probably make this faster.