PHP Basics

PHP #6: Even More Control Structures

0

So far we have learned about the following control structures:

  1. if, elseif, else
  2. while
  3. for

But there are still more. We'll first look at the switch construct.

Switch

The syntax for a switch statement looks something like this:

switch (expression) {
    case value1:
        //some code
    case value2:
        //some code
    case value3:
        //some code
    default:
        //some code
}

When this code is executed, each case is looked at in order. If(value1 == expression), then all code under that case and the code under all subsequent cases will be executed. If not, it will check if(value2 == expressions) and so on. If none of the cases match, the default case is used. You can have as many or as few cases as you want, and having the default case is optional. An important thing that is often forgotten is that all code underneath a true case is executed, even the code within the following cases.

$n = 3;
switch($n){
    case 0:
        print "$n is equal to 0\n";
    case 1:
        print "$n is less than or equal to 1\n";
    case 2:
        print "$n is less than or equal to 2\n";
    case 3:
        print "$n is less than or equal to 3.\n";
    case 4:
        print "$n is less than or equal to 4.\n";
    case 5:
        print "$n is less than or equal to 5.\n";
}

When the above code is executed, the following will be printed:

3 is less than or equal to 3.
3 is less than or equal to 4.
3 is less than or equal to 5.

Notice that once an appropriate case is found, all code in the following cases is executed as well. There is a way to prevent this though. Using the break; command you can jump to the closing brace of the switch statement preventing any more code from being executed.

Also, a default case will be used when no other cases match.

switch ($n) {
    case 0:
        print "$n is zero.";
        break;
    case 1:
    case 4:
    case 9:
        print "$n is a perfect square.";
        break;  
    case 2:
        print "$n is an even number.";
    case 3:
    case 5:
    case 7:
        print "$n is a prime number.";
        break;
    case 6:
    case 8:
        print "$n is an even number.";
        break;
    default:
        print "Only single-digit numbers are allowed.";
        break;
}

Test for Understanding

  1. What will print if $n is set to 7?
  2. What will print if $n is set to 1?
  3. What will print if $n is set to 20?

Answers:

  1. 7 is a prime number.
  2. 1 is a perfect square.
  3. Only single-digit numbers are allowed.

PHP #5: More Loops

0

There are a few other types of loops in addition to while loops that we learned about in Part 4.

Do-While Loop

A do-while loop is very similar to a while loop. The only difference is that the condition is evaluated after each loop iteration, rather than before. The syntax is like this:

do {
  // some code here
} while (condition)

Since the condition isn't evaluated until after the loop body, the loop body is always executed at least once, whether or not the condition is true. Once it does get to the condition, if it is true, it goes back up to the top of the loop body. If it is false, the loop terminates.

$i = 11;
do {
   print "The number is $i<br />";
   ++$i;
} while ($i <= 10)

The above code prints:

The number is 11&lt;br /&gt;

even though the condition is not true. The loop body always executes once.

For Loop

The for loop is a bit more complicated. The syntax looks like this:

for (initial-expression; condition; loop-end-expression) {
  //some code goes here
}

The initial-expression is evaluated only once, at the very beginning of the loop. The condition is then evaluated. If the condition is true, the body of the loop executes. Then the loop-end-expression is run. The process then starts over again with evaluating the condition. A for loop is generally used to do simple bounding loops, like this:

for ($i = 1; $i <= 10; ++$i) {
   print "The number is $i<br />"
}

As you'll notice, the same exact thing can be done with a while loop, but many prefer the for loop as it is more compact:

$i = 1;
while ($i <= 10) {
   print "The number is $i<br />";
   ++$i;
}

More Looping Examples

Let's try using a for loops to create a multiplication table.

$start = 1;
$end = 10;

print '<table border="1" cellspacing="0" cellpadding="5">';
for ($y = $start - 1; $y <= $end; ++$y) {
	print "<tr>";
	for ($x = $start - 1; $x <= $end; ++$x) {
		if ($y == $start - 1) {
			print "<td><b>$x</b></td>";
			
		} else if ($x == $start - 1) {
			print "<td><b>$y</b></td>";
		} else {
			print "<td>"
            print $x*$y;
            print "</td>";
		}
	}
	print "</tr>";
}
print "</table>";

Notice that there is a for loop inside of another for loop. These are called nested for loops. The outer loop loops through each row, and while the inner loop loops through each column. This means on every iteration of the outer loop, the entire inner loop runs. Trace the above code carefully to see how it works. This code will produce the following table:

0 1 2 3 4 5 6 7 8 9 10
1

1 2 3 4 5 6 7 8 9 10
2

2 4 6 8 10 12 14 16 18 20
3

3 6 9 12 15 18 21 24 27 30
4

4 8 12 16 20 24 28 32 36 40
5

5 10 15 20 25 30 35 40 45 50
6

6 12 18 24 30 36 42 48 54 60
7

7 14 21 28 35 42 49 56 63 70
8

8 16 24 32 40 48 56 64 72 80
9

9 18 27 36 45 54 63 72 81 90
10

10 20 30 40 50 60 70 80 90 100

Test for Understanding

  1. In the code above how many times does line 6 run?
  2. In the code above how many times does line 8 run?

Answers:

  1. Line 6 runs while $y <= 10. $y starts at 0 ($start - 1) and goes up by 1 each time. So it runs while $start = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. That's 11 times!
  2. Line 8 runs on every iteration of the inner loop. The inner loop runs while $x <= 10. $x starts at 0 and goes up by 1 each time. So the inner loop runs 11 iterations. But the inner loop happens again on every iteration of the outer loop, which also iterates 11 times. 11 x 11 = 121 times.

PHP #4: While Loops

1

In programming, loops are used to execute the same lines of code multiple times. The simplest type of loop is called a while loop. The lines of code in the body of a while loop will continue executing over and over WHILE the condition is true. The syntax looks like this:

while (condition) {
   //run this code repeatedly while the condition is true
}

Just like with if statements, the condition is evaluated as a boolean. If the condition is true, the block of code is executed and then it starts over my evaluating the condition again. If the condition is false, the block of code is not executed and the loop is terminated. Let's try making a loop that will print all the numbers from 1 to 10:

$i = 1;
while ($i <= 10) {
   print "The number is $i<br />";
   $i = $i + 1;
}

We start with a variable $i that we have set at 1. 1 is less than or equal to 10 so the loop body executes. "The number is 1<br />" is printed to the HTML, and then we add 1 to the variable $i. Now the condition is checked again, but this time $i is 2. 2 is still less than or equal to 10, so the loop body executes again. This continues and each time the number is printed and 1 is added to $i. Once $i gets to 11, the condition is no longer true, so the loop terminates.

A word about incrementing

When dealing with loops it is common to have an indexing variable, like $i in the previous example. Usually you will want $i to either increase by one or decrease by one on each iteration of the loop. In the previous example, we used $i = $i + 1; to do this, but there is a simpler way that accomplishes exactly the same thing:

++$i;

This is called the pre-increment operator. There is also a pre-decrement operator that will subtract one from the variable:

--$i;

Important Note: A common misconception is that ++$i is the same thing as $i + 1. They are not the same. ++$i actually changes the value of $i to be 1 greater. $i + 1 keeps $i as is, but gives you the number 1 greater than $i to use as a value.

With that said, we can rewrite our loop above using the pre-increment operator:

$i = 1;
while ($i <= 10) {
   print "The number is $i<br />";
   ++$i;
}

This loop accomplishes exactly the same thing as the previous one.

More Looping Examples

Looping can be used to accomplish a lot of different things.

In mathematics, the factorial of a positive non-decimal whole number is the product of all positive non-decimal numbers less than or equal to it. For example:
5 Factorial = 1 * 2 * 3 * 4 * 5 = 120

We can use a while loop to calculate the factorial of a number:

$i = 5; //the number to calculate the factorial of
$factorial = 1;
while ($i > 0) { //once $i is no longer a positive integer, stop looping
   $factorial = $factorial * $i;  //multiply by the current number
   --$i;  //go down to the next number
}
print $factorial;

This will print the number 120, the factorial of 5. If we want 10 factorial, all we have to do is change the initial value of $i, and our code will do the rest.

Now let's apply what we learned in PHP #2: GET and POST to ask a user what number they would like to know the factorial of. First we'll need an html form where the user enters the number:

<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<form method="get" action="factorial.php">
     Calculate the factorial of:<input type="text" name="factorial" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

Now we'll create a php file called factorial.php that will process the info from the form using the same method as before.

<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<?php
$i = $_GET['factorial']; //the number to calculate the factorial of
$factorial = 1;
while ($i > 0) { //once $i is no longer a positive integer, stop looping
   $factorial = $factorial * $i;  //multiply by the current number
   --$i;  //go down to the next number
}
print "The factorial is $factorial.";
?>
</body>
</html>

Now view the html page in your browser and you should have a functioning factorial calculator. You can download the full source code for this example here:
Factorial Example
Factorial Example
Size: 1.17 KB

PHP #3: If, Else If, Else Statements

0

Welcome to part 3 of these basics of PHP tutorials. In this part, we are going to learn how to make if statements.

The syntax for an if statement look like this:

if (condition) {
     //Run this code if condition is true
}

Where it says "condition" we insert a Boolean expression, an expression that either has a value of true or false. If the condition is true, the code inside the brackets will be executed. Here's an example:

if (3 > 2) {
     //This code would run because 3 is greater than 2
}

The Boolean expression 3>2 would return true, because 3 is greater than 2. Since it is true, the code inside the brackets would be executed. After the code in the brackets is executed, it would continue executing any code after the closing bracket.

Now consider this:

if (2 > 3) {
     //This code would not run because 2 is not greater than 3
}

The Boolean expression 2>3 would return false, because 2 is not greater than 3. Since it is false, the code inside the brackets would be skipped and any code after the ending bracket would continue on being executed.

Of course there are many other comparison operators besides > that you can use as well.

  • > returns true if the value to the left is greater than the value to the right.
  • >= returns true if the value to the left is greater than or equal to the value to the right
  • < returns true if the value to the left is less than the value to the right.
  • <= returns true if the value to the left if less than or equal to the value to the right.
  • == returns true if the value to the left is equal to the value to the right.
  • != returns true if the value to the left is not equal to the value to the right.

We can use variables for comparison as well.

if ($value == $value2) {
     print "$value equals $value2";
}

You can add another block of code called "else" that executes if the condition is not true.

if ($value == $value2) {
     print "$value equals $value2";
} else {
     print "$value does not equal $value2";
}

You can even add more blocks of code that execute if the initial condition statement is false, but another condition is true:

if ($value == $value2) {
     print "$value equals $value2";
} elseif ($value < $value2) {
     print "$value is less than $value2";
} else {
     print "$value is greater than $value2";
}

You can also combine multiple conditional statements into one.

if ($value == $value2 && $value2 == $value3) {
     print "$value, $value2, and $value3 are all equal"
} elseif ($value == $value2 || $value2 == $value3) {
     print "$value is equal to $value2 and/or $value2 is equal to $value3"
}

A statement consisting of two statements joined by && will only return true if both statements are true.
A statement consisting of two statements joined by || will return true if either of one of the two statement is true, or if both are true.

PHP #2: GET and POST

3

If you’re new to PHP make sure you to go back and read the first part of this tutorial before continuing.

In this tutorial we are going to learn about how to get data from an HTML form (inputted by a user) so that we can use that data in a PHP script.

There are two methods of getting data from HTML forms.  If you have browsed the web for any length of time before, you probably have seen the results of these methods in action.

The GET Method

When you see a URL that has a bunch of text and question marks and equal signs after the actual name of the file, they are using the GET method.  For example when you type in something on google and search you get a url like http://www.google.com/search?hl=en&q=AtomicPages+Hosting; that’s because they are using the GET method.  The part before the ? is the normal url to the page, but the part after that is actually passing data.  Each piece of data is made up of the name of the piece of data and the data itself (the value), separated by an equals sign.  Each pair of name and value pair is separated by an ampersand.  In the page http://www.google.com/search?hl=en&q=AtomicPages+Hosting there are 2 name/value pairs:

The first is named hl and has the value en.  In google’s case, they use this value to specify to the page which language you are searching in.  en stands for english.  If you leave that URL exactly as it is, except change it to say hl=fr, you’ll notice google will change to french.

The second name/value pair is called q and has a value of AtomicPages+Hosting.  This name/value pair is letting the page know what you typed in in the search box on the previous page, so that this page can display the results for that search.

Let’s do our own example of the GET method.  We will first make a simple HTML page called yourname.html containing just an ordinary HTML form.

<html>
<head>
<title>Your Name</title>
</head>
<body>
<form method="get" action="yourname_processor.php">;
     Enter your First Name: <input type="text" name="fname" /> <br />
     Enter your Last Name: <input type="text" name="lname" /> <br />;
<input type="submit" name="submit" value="Submit" />;
</form>
</body>
</html>

Notice the method attribute of the form tag.  We set it to get so that the browser knows the use the GET method.  We also set the action to yourname_processor.php which will be the page that gets passed the input data that will we create next.  The browser will use the value of the name attribute in the input tags to name each input value.  So if somebody fills out this form with John as the first name and Smith as the last name, and presses the submit button they will be moved to a url that looks something like this: http://www.example.com/yourname_processor.php?fname=John&lname=Smith

In PHP you can get the value of variables submitted to the page with the GET method by using the name from the url, like so:

$_GET[name]

Let’s now make yourname_processor.php so that it displays the person’s name that they entered in yourname.html.

<html>
<head>
<title>Your Name</title>
</head>
<body>
<?php
     $firstname = $_GET['fname'];
     $lastname = $_GET['lname'];
     print "Your name is $firstname $lastname";
?>
</body>
</html>

This code takes the values from the get method and set’s them to variables called $firstname and $lastname.  Then it prints out these variables in a string, as we learned how to do in the previous tutorial

The POST Method

The code for the post method will look almost exactly the same as the GET.  The big difference is that in the POST method, the passed data won’t be displayed in the URL.  The data is passed secretly.  Let’s make the same example again using the POST method.

yourname.html would look like this:

<html>
<head>
<title>Your Name</title>
</head>
<body>
<form method="post" action="yourname_processor.php">
     Enter your First Name:<input type="text" name="fname" /><br />
     Enter your Last Name:<input type="text" name="lname" /><br />
     <input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>

And yourname_processor.php would look like this:

<html>
<head>
<title>Your Name</title>
</head>
<body>
<?php
     $firstname = $_POST['fname'];
     $lastname = $_POST['lname'];
     print "Your name is $firstname $lastname";
?>
</body>
</html>

Unlike with GET, when you click the submit button on yourname.html you will be redirected to the exact same URL everytime, no matter what you entered.  The URL will always look like this http://www.example.com/yourname_processor.php with no name/value pairs on the end.  If you have ever pressed a back button on your browser and received a message that says something like “This page contains POST data, would you like to send the POST data again?”  This is because along with just sending you to this url, some data was also sent through the POST method.

GET vs. POST

There are pros and cons to both and they are both better to use in certain situations.  With GET method, the URL will be linkable and the data will be retained if somebody links you to the page.  With POST, if you try to link somebody to the page, the POST data won’t come with the link.

With POST however, data is kept more secure.  If you had somebody enter in a password, you would definitely want to use POST so that the password isn’t visible in the URL of the next page.

Go to Top