Hey all,

I have a problem with the following code i have written and was wondering if anyone can help?

The function below works fine if you define more than 2+ possible 'responses'. BUT, if theres only 1 'response' defined it wont work correctly. According to the PHP function 'array_rand($foo, number)', if no 'number' is set, the default is 1. So i have tried removing the value '2' in the function array_rand($myOutArray,2) but then the function wont work.

Any suggestions on what have i done wrong, i am sure i have overlooked something!

Thanks for any help. 🙂


<?php


// Define the message,

$message = "Hello everyone!";


// Create an array of keywords that we want to search for in the message

$keyword=array(
"hello",
"hi",
"hey"
);


// Create an array of random responses

$response=array(
"Hey there!",
"Hello!",
"Hi!"
);



// This is the function which searches the message for any keywords and displays a random 
// response if any keyword is found in the message (does nothing if no matches found, which is ok).

   function checkForWord($myFindArray, $myOutArray, $message){

  foreach ($myFindArray as $val) {

     $pos = strripos($message,$val);

        if ($pos !== false) {

           $random_keys = array_rand($myOutArray,2);
           $result = $myOutArray[$random_keys[0]];
           return $result;

        }

  }


   }


// Calls the function,

echo checkForWord($keyword, $response, $message);


?>

    If you wouldn't mind, it might benefit others in the future who come across this thread while searching if you would briefly describe (or show) what you did to fix this particular issue.

    Also, don't forget to mark this thread resolved.

      If you wouldn't mind, it might benefit others in the future who come across this thread while searching if you would briefly describe (or show) what you did to fix this particular issue.

      Also, don't forget to mark this thread resolved.

        Write a Reply...