-
<?php
-
if (1 == 1) {
-
echo '1 really does equal 1!';
-
}
-
?>
Alright, this is probably the easiest if statement you will ever see, it doesn't even have an else part to it. If you can't understand this (which I hope you can) then I will explain it, all it's doing is saying if 1 is equal (using 2 equal signs is how you define equal to) to 1 then continue, and all we do is echo out a simple statement. You can do anything though, you don't have to echo. Then we end the statement. Now let's use the same thing but add on an else, so if it doesn't equal one we have somewhere to go.
phpsu
-
<?php
-
if (1 == 1) {
-
echo '1 really does equal 1!';
-
} else {
-
echo 'Aww, 1 doesn\'t equal 1.';
-
}
-
?>
As you can see, all we did was add on } else { then add another echo statement. Pretty straight forward, but let's say we are using variables, we can make another tiny bit more complicated example.
-
<?php
-
-
$number = 1;
-
$answer = 2;
-
-
if ($number == $answer) {
-
echo '1 really does equal 1!';
-
} else {
-
echo 'Aww, 1 doesn\'t equal 1.';
-
}
-
?>
We use variables in this example, we have a number variable ($number) and an answer variable ($answer), we define static data to these variables, meaning they don't change, but that will be different when you start getting into MySQL and such. www.phpsu.com
Then instead of comparing 2 numbers in our if statement, we compare our 2 variables. Pretty much the exact same thing, except now our variables both contain different numbers so our output will then be Aww, 1 doesn't equal 1. because our 2 variables did not equal each other, so we go to our else statement.
This is just the basics of if statements, but this is also just a basic PHP tutorial. If you want to learn more about if statements check out any of the tutorials on this site, chances are they use if statements in them.
phpsu提供的php教程
Now let's check out switch conditionals, these are in theory the same as if statements except they allow you to have a lot of different answers to them. Here, I will show you a simple example first - www.phpsu.com
-
<?php
-
$var = 'Cows';
-
-
switch ($var) {
-
case 'Dogs';
-
echo 'You chose dogs!';
-
break;
-
case 'Cats';
-
echo 'You chose cats!';
-
break;
-
case 'Cows';
-
echo 'You chose cows!';
-
break;
-
case 'Birds';
-
echo 'You chose birds';
-
break;
-
default:
-
echo 'You didn\'t choose any animals!';
-
break;
-
}
-
?>
TITLE:PHP Conditionals (if statements)