Friday, June 19, 2009

PHP Control Structures

Conditional statements

Like many other programming languages, PHP includes several different controlstructures that can be grouped into two different areas: conditional statements and loops. In the following tutorial, I will give you some examples of each and show you when to use them. So let's start with the conditionals.

If
"If" is used whenever some PHP or HTML code needs to be executed based on one condition.

<?php
if ($myvariable == 1) print "Hello!";
?>

This means "Print the string 'Hello!' if the variable $myvariable is equal to 1" (note the double equal signs!). If you want to execute more than one line of code, just use a code block:

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
?>

In the above example, you tell PHP to "print the string 'Hello!' AND set the variable $othervariable to 2 if the variable $myvariable is equal to 1". You can even use if statements inside of other ifs if you like:

<?php
if ($myvariable == 1)
{
if ($othervariable == 2)
{
print "Hello!";
}
}
?>

This one checks if $myvariable equals 1. If this is true, it checks if $othervariable equals 2, and if this is also true, PHP will print "Hello!". There IS a better way to accomplish the above example with less code using other operators (I'll get to that in a short while) but let's first stick with other ways of using "if". So what if you want to execute other code if the given condition is NOT true? Well, just use "else":

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
else
{
print "Goodbye";
}
?>

Here, PHP will print the string "Goodbye" whenever $myvariable is something other than 1. If there are more than two code blocks you want to execute based on different conditions, you can use "elseif":

<?php
if ($myvariable == 1)
{
print "Hello!";
$othervariable = 2;
}
elseif ($myvariable == 2)
{
print "Have fun!";
}
else
{
print "Goodbye";
}
?>

So now, PHP will check if $myvariable equals 1. If it isn't, it will check if $myvariable is 2, and if it is neither 1 or 2, PHP will print "Goodbye". You see that those constructs can be very long, for example if you want your script to act differently if $myvariable is 1, 2, 3, 4, etc. A shorter way to accomplish that is using the switch statement which I will discuss in a short while. But first, let me show you the different operators that can be used inside the most important control structures (so far we only used the double equal sign "==") and a funky new way of using "if".

Operators








Let me give you a quick example for the "and", "or" and "not" operators:

<?php
if (($myvariable < 10 && $myvariable > 5) || !(
$othervariable = 1))
{
print "Yeah!";
}
?>

Can you see what that does? It means: "Print 'Yeah!' EITHER if $myvariable is less than 10 and greater than 5 OR if $othervariable is NOT equal to 1". Note that you can also write "$othervariable != 1" as the second condition. Now here's a slick little line of code for those of you who don't like long code fragments. Suppose you want to have an if statement that does this: "Check if $myvariable is 1. If that is true, change the value of $fruit to 'apple' else to 'banana'". Now that you know how to use if, you'd probably do it like this:

<?php
if ($myvariable == 1)
{
$fruit = 'apple';
}
else
{
$fruit = 'banana';
}
?>

There's another way, called the "ternary operator":


<?php
$fruit = ($myvariable == 1) ? 'apple' : 'banana';
?>

That's it! Yes, I admit, it looks wild, but once you see how it works it's nice to use. You always use it like this:

<?php
$variable =
(condition) ? 'value_if_condition_is_true' :
'value_if_condition_is_false'
?>

Switch

OK, time for "switch". Whenever you have many different code blocks that need to be executed based on different conditions of a variable, it's best to use "switch". An example? OK, here we go:


<?php
switch ($myvariable)
{
case 1:
print "One";
break;
case 2:
print "Two";
break;
case 3:
print "Three";
break;
default:
print "Other number";
}
?>

This one checks $myvariable and prints "One" if it's value is 1, "Two" if it's 2, "Three" if it's three and "Other Number" if it's something else (the "default" branch). But what about the "break;"? It stops the execution of the switch command! If you wrote the switch without the breaks, it would act differently. Check this out:


<?php
switch ($myvariable)
{
case 1:
print "One";
case 2:
print "Two";
case 3:
print "Three";
default:
print "Other number";
}
?>

So let's say $myvariable equals 2. What will happen? Well, this script will print out: "TwoThreeOther number". Can you see why? Since $myvariable equals 2, the script prints out "Two". But because we didn't input the "break" commands, it executes all other lines inside the switch, too!

Loops

Alright, time for loops! Whenever you want something done over and over, loops are the control structures of choice. One example for using loops is reading line by line from a text file. So first I'll just show you the simplest loop there is: while!

While loops

<?php
$myvariable = 0;
while ($myvariable < 10)
{
print "HELLO!";
$myvariable++;
}
?>

This one means "as long as $myvariable is smaller than ten, print out 'HELLO!' and add one to $myvariable". So this example will print out "HELLO!" ten times. If we'd set $myvariable to ten before the while loop, it would not have printed out anything. But what if we want PHP to print out at least one "HELLO!" in any case? Check this:

Do Loops

<?php
$myvariable = 10;
do
{
print "HELLO!";
$myvariable++;
}
while ($myvariable < 10);
?>

Can you see the difference? If you use a do loop, the condition (in this case
"$myvariable < 10") is checked AFTER the code within the loop has been processed
once! So in the above example, you will see one "HELLO!". Ready to look at a more
complex loop? OK, here we go!

For loops

Let's use the "HELLO!" example again:

<?php
for ($countervariable = 0; $countervariable < 10;
$countervariable++)
{
print "Hello!";
}
?>

Can you imagine what happens inside the parentheses? Right, PHP initializes $countervariable and gives it the value zero. Then it starts looping. With each loop, it is checked whether $countervariable is smaller than ten and if that is true, "HELLO!" is printed and $countervariable is increased by one! Whenever you know how many loop cycles you need, it's best to use a for loop.