1

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?

1
  • This "strpos" has made me confused :( Commented Aug 13, 2012 at 6:37

2 Answers 2

1

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect - remember to accept the answer, so others will see the comment on the top of the thread if the search for the same: meta.stackexchange.com/questions/5234/…
0

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;
}

Comments

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.