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.