PDA

View Full Version : Making sure a variable is only a certain word.


ole90
09-18-2007, 05:46 PM
//Lets check that train contains only: health, strength, defence, accuracy
if($traintype != "health") {} elseif ($traintype != "strength") {} elseif ($traintype != "defence") {} elseif ($traintype != "accuracy") {} else {
$input = "Wrong Training Type.";
error($input);
}

$traintype is a _Get variable gotten from the url so the user can edit it.

The code above doesn't seem to work because it still allows me to enter anything the in the url and doesn't stop the script.

Any ideas ;X?

Inigoesdr
09-18-2007, 05:57 PM
That should be $traintype == "health" because when PHP gets to the first one it will evaluate to true if it's anything other than health. Compare the possibilities with == and then have your else for anything.. else.

ole90
09-18-2007, 06:04 PM
Ooooh yeah :X Thanks!

aedrin
09-18-2007, 06:22 PM
That is the wrong way of doing things, by the way. Don't use an empty code block as it's confusing to read, especially if you add single line statements (those not enclosed in curly brackets) as the else part.

Consider using an array to hold your words, then use http://us3.php.net/in_array to check whether the word is in the array.


$words = array('array', 'word', 'yes', 'no');

if (in_array('word', $words)) {
echo 'The word was found!';
}

Inigoesdr
09-19-2007, 01:05 AM
I presumed that ole90 was going to be putting code in there, but aedrin's right about that.