Page 1 of 1

Need help with stristr statement with 6 conditions

Posted: Fri Feb 26, 2010 2:08 pm
by wjarrett
I am new to php and am seeking an answer to this problem.
I am trying to write and evaluative script that searches a submitted string
known as $response for six seperate values which must all be present for the
response to be correct. I am unsure as to how I should be expressing this properly.
This is as close to a proper expression as I can seem to get. I have found many
examples of how to find one needle in a haystack but how do you find all six?

Code: Select all

 
<?php
 
$response = $_POST[Q1Answer];
 
if (stristr($response,'magna carta')) &&!(stristr($response,'mayflower compact')) &&!(stristr($response,'declaration of independence')) &&!(stristr($response,'articles of confederation')) &&!(stristr($response,'constitution')) &&!(stristr($response,'bill of rights')) 
{
echo "You wrote ";
echo $response;
echo " That is Correct";
}
else 
{
echo "You wrote ";
echo $response;
echo " That is Incorrect";
}
 
?>
 
Losing my mind over this for two days now. Any help is appreciated.
:banghead:

Re: Need help with stristr statement with 6 conditions

Posted: Fri Feb 26, 2010 6:43 pm
by AbraCadaver
From a glance, remove the ! NOT operators and it should work, however I would use stripos():

Code: Select all

if ((stripos($response,'magna carta') !== false) &&
    (stripos($response,'mayflower compact') !== false) &&
    (stripos($response,'declaration of independence') !== false) &&
    (stripos($response,'articles of confederation') !== false) &&
    (stripos($response,'constitution') !== false) &&
    (stripos($response,'bill of rights') !== false))
{
    echo "You wrote ";
    echo $response;
    echo " That is Correct";
} else {
    echo "You wrote ";
    echo $response;
    echo " That is Incorrect";
}
If you do this more than once, then I would build a function to put in my functions.php that I include on every page:

Code: Select all

$required = array('magna carta', 'mayflower compact', 'declaration of independence', 
                  'articles of confederation', 'constitution', 'bill of rights');
 
if(match_required($required, $response)) {
    echo "You wrote ";
    echo $response;
    echo " That is Correct";
} else {
    echo "You wrote ";
    echo $response;
    echo " That is Incorrect";
}
 
function match_required($needles=array(), $haystack='') {
 
    foreach($needles as $needle) {
        if(stripos($haystack, $needle) === false) {
            return false;
        }
    }
    return true;
}
As an aside, you need to quote string array indexes:

Code: Select all

$response = $_POST['Q1Answer'];