If/Else Statements
If statements!
This is probably the most important section so far (I'll probably say that more and more from this point on). Now we teach your scripts logic! After this can can make some basic decisions. Let's take a look at an If statement:
<?PHP
if () //Conditional goes in there
//If it's true then do something
?>
This basically says, in human terms:
If something is true
then do this.
Everything in the next is run if the statement in the perenthsis is a true statement.
Let's talk quickly about boolean. For now there's not much to get into. Here some conditionals:
This one is the only tricky one, if you wanted to say if $x equal '1' you have to use double "=" because a single "=" is an assignment statement not a comparison.
<
if the first operand is smaller than the second operand.
>
if the first operand is bigger than the second operand.
!=
if the first operand is not equal to the second operand.
We will cover more complicated boolean structures later, for now, this serves our purpose.
So, confused yet? No problem, we'll put it together now in a way that's hopefully more understandable. Let's do a quick case study. Let's make a script that determines whether a student passed or failed a class. Let's say that anything 60 or above is passing and anything below is failing.
<?PHP
$grade = 65;
if ($grade > 59 )
echo "Pass";
if ($grade < 60 )
echo "Fail";
?>
If you run this code it will return the word "Pass"
It's important to note that an if statement will run the next line if it evaluate to 'true' but you can make it run more than just one line by using curly brackets. This is a proper segue to the next section...
... and the 'else' statement
So you just learned the if statement. Now what if you wanted to define what happens as an alternative to the statment evaluating to true? Use else! Take a glance at this:
<?PHP
$grade = 65;
if ($grade > 59 )
echo "Pass";
else
echo "Fail";
?>
This essentially does the same thing as the last example on the last section. It saves a few lines of code and you'll find that this makes much more sense sometimes. The else statement does not use a semicolon. Use one and you'll get a nasty error message. The else statement can also make use of curly brackets to run multiple lines of code.