Forum Moderators: coopster
if ($var == 'a') {
// $var is a
} elseif ($var == 'b') {
// $var is b
} else {
// $var is anything else
}
But I suggest you to look into the use of switch() [php.net] statement, as that is much more suitable for similar 'problems'.
if ($foo == "a") {
echo "do a";
} elseif ($foo == "b") {
echo "do b";
} else {
echo "do neither a nor b";
}
or this:
if (($foo == "a") ¦¦ ($foo == "b")) {
echo "do a or b";
} else {
echo "do neither a nor b";
}
or this:
if ($foo == "a") {
echo "do a";
}
if ($foo == "b") {
echo "do b";
}
if (!($foo == "a") &&!($foo == "b")) {
echo "do neither a nor b";
}
Over an array with 20000 values the difference with a default was about 0.25 seconds with my set up.
[edited by: PHP_Chimp at 4:25 pm (utc) on Dec. 11, 2007]
Here is an example though to help your understanding:
<?php// $var = the value/letter chosen (example: a,b,c,d,e..)
switch ($var):
case a:
// call function / do something here
break;
case b:
// call alternative function / do something else here
break;
default:
// default action / call default function action
endswitch;
?>
I hope this helps you :)
switch ($var):
case [b]'[/b]a[b]'[/b]:
// call function / do something here
break;
case [b]'[/b]b[b]'[/b]:
// call alternative function / do something else here
break;
default:
// default action / call default function action
I love switch statements, they just look more ordered than if/elseif/else, but if speed is an issue then use the fastest version as they give the same results.
what if it is a number or more the one letter?
If this isn't possible because of form validation or just doesn't matter then don't worry about it.
But the post asked how to see if it is any other single letter...
which would require somthing like (sorry for bad php but I don't know it well)
var_is_good = True
if ($var.length() > 1){
// $var is not a single letter
// var_is_good = False
}
if ($var.isAlpha() == False){
// $var is not a letter at all.
// var_is_good = False
}
if (var_is_good!= False){
if ($var == 'a') {
// $var is a
} elseif ($var == 'b') {
// $var is b
} else {
// Now $var is any other SINGLE letter.
}
}
That will make sure the input is a single letter before determining what letter it is.
[edited by: Demaestro at 9:53 pm (utc) on Dec. 12, 2007]