Question

How can I check if a string contains a member of an array, and return the index (integer) of the relevant member?

Let's say my string is this :

$string1 = "stackoverflow.com";
$string2 = "superuser.com";
$r = array("queue" , "stack" , "heap");

get_index($string1 , $r); // returns 1
get_index($string2 , $r); // returns -1 since string2 does not contain any element of array

How can I write this function in an elegant (short) and efficient way ?

I found a function (expression ? ) that checks if the string contains a member of an array :

(0 < count(array_intersect(array_map('strtolower', explode(' ', $string)), $array)))

but this is a boolean. does the count() function return what I want in this statement ?

Thanks for any help !

Was it helpful?

Solution

function get_index($str, $arr){
    foreach($arr as $key => $val){
    if(strpos($str, $val) !== false)
    return $key;
    }
return -1;
}

Demo: https://eval.in/95398

OTHER TIPS

This will find the number of matching elements in your array, if you want all matching keys, use the commented lines instead:

function findMatchingItems($needle, $haystack){
    $foundItems = 0; // start counter
    // $foundItems = array(); // start array to save ALL keys
    foreach($haystack as $key=>$value){ // start to loop through all items
        if( strpos($value, $needle)!==false){ 
            ++$foundItems; // if found, increase counter
            // $foundItems[] = $key; // Add the key to the array
        }
    }
    return $foundItems; // return found items
}

findMatchingItems($string1 , $r);
findMatchingItems($string2 , $r);

If you want to return all matching keys, just change $foundItems to an array and add the keys in the if-statement (switch to the commented lines).

If you only want to know if something matches or not

function findMatchingItems($needle, $haystack){
    if( strpos($value, $needle)!==false){ 
        return true;
        break; // <- This is important. This stops the loop, saving time ;)
    }
    return false;// failsave, if no true is returned, this will return
}

I would do a function like this:

function getIndex($string, $array) {
    $index = -1;
    $i = 0;
    foreach($array as $array_elem) {
        if(str_pos($array_elem, $string) !== false) {
            $index = $i;
        }
        $i++;
    }
    return $index;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top