如何将数组中的文本与字符串匹配,如果为true则返回其值?

如何将数组中的文本与字符串匹配,如果为true则返回其值?

问题描述:

I'm trying to understand how I can match an array against a line of text, if the text inside the array is found, then I'd like to return that value.

I've tried the following but nothing seems to get returned.

$catArray = array(
    '0' => 'breakfast',
    '1' => 'lunch',
    '2' => 'dinner',
);

$text = 'It is your breakfast';

foreach($catArray as $cat){
    if(strpos($cat, $text) !== false){
        return $cat;
    }
}

By this logic, breakfast should return.

$catArray = array(
    '0' => 'breakfast',
    '1' => 'lunch',
    '2' => 'dinner',
);
$text = 'It is your breakfast';

foreach($catArray as $cat){
    if(strpos($text, $cat) !== false){
        echo $cat;
    }
}

returns breakfast

so basically turn around the haystack and the needle

You are doing it in a wrong way, also you are returning the variable instead of printing. here is the correct syntax:

strpos(<srting>,<find>,<start-optional>)

i modified your code, now it is working.

$catArray = array(
    '0' => 'breakfast',
    '1' => 'lunch',
    '2' => 'dinner',
);

$text = 'It is your breakfast';

foreach($catArray as $cat){
    if(strpos($text, $cat) !== false){
        echo($cat);
    }
}