user1588878
user1588878

Reputation: 109

strpos with array_key_search

i have a code to search for array keys, but only if the message is the exact message, i want it to use strpos so it can detect the message but i don't know how to do it:

My Code:

$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (array_key_exists($message,$responses)){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}

So this only works if the whole posted data was "hi". I want it to use strpos so it can detect hi anywhere, how would i do that?

Upvotes: 1

Views: 4592

Answers (2)

Myd
Myd

Reputation: 103

strpos(firststring,secondstring,startposition[Optional]) function is return num.if num>=0 mean second string in first string.

$message = $_POST['message'];
$responses = array("hi" => "whats up?");
if (strpos($message,$responses)>=0){
$msg = strtolower($message);
$answer = $responses[$msg];
echo $answer;
}

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39542

I'm not 100% sure, but is this what you want?

$foundKey = null;
foreach ($responses as $key => $value) {
    if (strpos($message, $key) !== false) {
        $foundKey = $key;
        break;
    }
}
if ($foundKey !== null) {
    echo "Found key: " . $responses[$key];
}

Edit:

If you want a case insensitive version, of course you can use this instead:

$foundKey = null;
foreach ($responses as $key => $value) {
    if (stripos($message, $key) !== false) {
        $foundKey = strtolower($key);
        break;
    }
}
if ($foundKey !== null) {
    echo "Found key: " . $responses[$key];
}

Upvotes: 1

Related Questions