0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Indeed, the entire array won't be parsed when a match is found in the middle. I see, thanks for your input and such a quick response.
How big is this array gonna get?
The array I'm going use won't get more than 100 keys(elements).
Then this won't be a problem what so ever performance-wise, unless your server runs on hamster. Looping a single-dimensional array hundred times or less is really not something you need to worry about.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.