Mystic
Mystic

Reputation: 157

PHP MYSQL ARRAY check if string is in array

I have user input which in this case will be Hello

$command = mysqli_real_escape_string($con,$_POST['command']);

a variable called $dialogue_unlock is populated through some scripts. Which for testing will output 'Hello','Goodbye'

$dialogue_unlock .= ',\''. $discuss_row['discussion_text'].'\'';

Im then trying to see if the user input matches the array

$dialogue_array = array($dialogue_unlock);
if(!in_array("$command", $dialogue_array)){
    $err .= 'Invalid Question';
}

As a test im using

echo $err. '<br>';
echo $command. '<br>';
echo $dialogue_unlock;

I get

Invalid Question
Hello
'Hello','Goodbye'

I just cant wrap my head around it as 'hello' is definitely in 'Hello','Goodbye'. Can anybody offer some advise please.

Many thanks.

Upvotes: 0

Views: 154

Answers (2)

Tutti Frutti
Tutti Frutti

Reputation: 101

Try this.

$command = mysqli_real_escape_string($con,$_POST['command']); /// hello
$dialogue_unlock .= ',\''. $discuss_row['discussion_text'].'\''; /// 'Hello','Goodbye'
$dialogue_unlock = explode(',', $dialogue_unlock); /// dialogue_unlock to array


foreach ($dialogue_unlock as $a) {
    if (strpos($command, $a) !== FALSE) { 
        echo "Match found"; 
    }
   else
    {
        echo "Not found!";
    }
}

Upvotes: 1

Nigel Ren
Nigel Ren

Reputation: 57121

It looks as though your array contains the 1 element with the text 'Hello','Goodbye' and when you look for Hello it doesn't match. What you should do is add each item of $discuss_row['discussion_text'] to $dialogue_array directly using (in whatever loop you build up $dialogue_unlock)

$dialogue_array[] = $discuss_row['discussion_text'];

So when you add Hello and Goodbye then it will be two separate elements in the array.

Just make sure that before this loop you initialise the array...

$dialogue_array = [];

Upvotes: 1

Related Questions