1

I have an array:

        $myArray= array(
        "Cold coffe", 
        "Cold water",
        "Disco", 
        "I love you"        
        );

And i have string:

$string = "My baby I love you"

I wanted to check if one of this values exsits in this string and i do it in this way:

        function match($needles, $haystack)
    {
        foreach($needles as $needle){
            if (strpos($haystack, $needle) !== false) {
                return true;
            }
        }
        return false;
    }


    if(match($myArray, $string)){
       echo "Matching.";
    }

And this works ok, but i want to know which one of this values in $myArray exsits in this string and print that value, how i can do that?

2 Answers 2

1

In your custom match function, you can return the matching string ($needle), instead of returning true. OP confirmed that he just needs the value.

function match($needles, $haystack)
{
    foreach($needles as $needle){
        if (strpos($haystack, $needle) !== false) {
            return $needle;
        }
    }
    return false;
}

Now, just print it out:

if( $needle = match($myArray, $string) ){
   echo "Matching Word: " . $needle;
}
Sign up to request clarification or add additional context in comments.

10 Comments

You dont explain which array key is used, How do you get the string from $myArray afterwards?
@delboy1978uk because I return the value directly. I dont need to use key to get the value afterwards from array.
You don't but the OP probably does. If he can confirm i'll reverse it.
@delboy1978uk OP does not want the key. Question is very clear that he is looking for the value in the array which matches.
Hey guys. I'm very thankful for your answers. I just want the value, not the key.
|
1

You just need to tweak your function slightly to use the array index:

<?php

 $myArray= array(
    "Cold coffe", 
    "Cold water",
    "Disco", 
    "I love you"        
    );

$string = "My baby I love you";

function match($needles, $haystack)
{
    foreach($needles as $index => $needle){
        if (strpos($haystack, $needle) !== false) {
            return $index;
        }
    }
    return false;
}


if($index = match($myArray, $string)){
   echo "Matching array key ".$index . ", " . $myArray[$index];
}

Output: Matching array key 3, I love you

See it here https://3v4l.org/JPNOF

Comments

Your Answer

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