Introducing Conditionals
Posted: March 2, 2009
Conditionals basically allow you to tell PHP what to do, depending on certain conditions. This is where you really start getting into PHP programming. This is where you’ll find the ‘If…Then’ you may have seen before in programming.
Conditionals aren’t too hard. The most basic form of a conditional is the ‘If’ statement.
If something is true…
Then do something else
In PHP this is written like so…
if (something) {
something else
}
Let’s look at an example.
$a = 2;
$b = 1;
if ($a > $b){
echo $a;
}
So in this example, we first test whether $a is greater than $b (using the > symbol again from Algebra). If this is true, we print the value of $a. In this case, the browser would see the number 2 because $a is indeed greater than $b.
However, say $b was equal to 3. In that case, we would not print the value of a, and the PHP interpreter would simply continue its merry little way on to the rest of the code.
You can put more than one statement in the curly braces of an ‘If’ statement, by the way. We could also have:
if ($a > $b){
echo ‘A is greater<br />’;
echo $a;
}
This would output:
A is greater
2
Notice I included the html <br /> in there. You have to include whatever html tags you need, including line breaks, inside the strings you send to PHP.
Now what if we wanted to test to see if $a and $b were equal? Well, like I mentioned in the previous section, we use two equals signs for this:
if ($a == $b){
echo ‘They are equal’;
}
If the two numbers are equal, and only if they are equal, the browser will see ‘They are equal’ printed.
However, as I warned before, you must be careful not to use the single equals sign for this.
if ($a = $b){
echo ‘They are equal’;
}
Because that will assign the value of $b to $a. So even if $a started out as 3 and $b started out as 56, this would be considered a true statement, because PHP would assign the value of 56 to $a, and then declare it a true statement. So our browser would always see ‘They are equal’ even if they are not.
Using our form example from a past lesson, we could display a message only if someone put ‘Fred’ in as their username.
if( $_POST[‘username’] == ‘fred’){
echo ‘Heya Fred!’;
}
So you can hopefully begin to see how some of the magic happens when you send that web form.








