Jump to content

Can anyone help with this php function? - array_rand($foo, number);


Scorpio

Recommended Posts

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 = "Where can i find the nearest hotel?";

 

 

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

 

$keyword=array(

"hotel",

"beach",

"hospital"

);

 

 

// Create an array of random responses

 

$response=array(

"Search Google",

"Search Yahoo",

"Search MSN"

);

 

 

 

// 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);

 

 

?>

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.