17 WEBSHOP [web design & development] +1 (940) 343-5183  

Webshop Blog

1

PHP From the Top: 3 (Loops and Conditions)

PHP Elephant Logo

So it’s been some time since our last segment, today we’re going to pick up where we left off with our PHP From the Top series and jump into some new topics. Loops and Conditions are called Control Structures and are a large part of what really makes your script dynamic, they allow the script to somewhat make its own decisions based on current circumstances. Let’s get started.

Other Posts in this Series

Conditions (If, Else Statements)

First, we’re going to take a look at conditional statements (or If, Else statements). If and else are two seperate statements, but they often work together hand in hand. To explain how this works, I think its probably best to first draw up an example and describe it rather than keep discussing in the abstract. Here’s a simple If, Else statement.

if( 1 < 2 ) {
     echo "1 is less than two";
} else {
     echo "1 is not less than two";
}

Okay, a few things to notice here: first, notice the expression in the parentheses after the if statement. This expression is what determines how the following code will be executed. If this expression evaluates to TRUE, the code in the if statement's braces will be executed. If this expression evaluates to FALSE, the code in the else statement's braces will be executed. In the above example, the script will echo "1 is less than two" because the expression if( 1 < 2 ) will always evaluate to true. Let's take a look at a few slightly more complex examples using variables.

$x = 2;
$y = 7;
if( $x > $y ) {
     echo "$x is greater than $y";
} else {
     echo "$x is not greater than $y";
}

This example will obviously evaluate to false and will echo "2 is not greater than 7".

$x = 5;
$y = 10;
if( $y - $x == $x ) {
     echo "$y - $x is equal to $x";
} else {
     echo "$y - $x is not equal to $x";
}

This example shows that you can perform mathematical calculations within the conditional expression. Another important thing to note about this example is the double equal sign operator == in the expression. This is known as the equality operator and is used to determine whether or not two values are equal to one another. There are actually a few different "equal sign-like" operators in the PHP language and it's important not to confuse them. Let's take a quick look at a few of them.

Assignment and Comparison Operators

Operator Description Example
= This is the assignment operator. Use this "single equal sign" to assign values to variables. $myName = 'Jordan';
== This is the equality operator. Use this "double equal sign" to compare the values of two variables and determine if they are equal to each other. if( 1 + 2 == 3 ) {
    echo "1 + 2 = 3";
}
=== This is the identical comparison operator. Use this "triple equal sign" to determine not only if two values are equal to one another but also to determine if both values are of the same type. In the first example to the right, both values are equal to 5 but the first variables type is int and the second variables type is string (notice the quotes). For this operator to evaluate to true both values must be equal to each other and be of the same type. $int = 5;
$str = '5';

if($int == $str) {
    //evaluates to true
}
if($int === $str) {
    //evaluates to false
}

!= This is a negation of the comparison operator. Use this to test if two values are not equal to one another. You can also use the <> operator, however it is much more common to use !=. if( 2 + 2 != 3 ) {
    //evaluates to true
}

These are just a few of the operators available to you in the PHP language, if you would like to reference a full list, check out the PHP Comparison Operators page at php.net.

Moving on to Loops

Loops are an interesting control structures, a loop allows a script to repeat a block of code a defined number of times. There are a few loops that are available in PHP, but we're only going to take a look at what are probably the two most common -- "For" loops and "While" loops.

While Loops

A simple While Loop looks something like this:

$i = 1;
while($i <= 10) {
     echo $i . "<br />";
     $i++;
}

The above script will print numbers from 1 to 10 on the screen. This introduces a few new and important concepts. First of all, the use of the variable $i: it is a very common practice to use the variable $i as what's called the iterator when working with loops. Using this variable allows the script to keep track of how many times the loop has been executed.

NOTE: It is very important to keep track of how many times a loop has been executed and to make sure that you have a defined a maximum number of times for the loop to run. Otherwise you may end up with an infinite loop which will cause your script to crash.

Second you should notice the ++ operator. This is the increment operator. It essentially takes the variables value and adds 1 to it. In other words, $i++; is the same thing as $i = $i + 1;. It is just a shorthand. Also available with the PHP language is the opposite of the increment operator--the decrement operator which is simply --, two subtraction signs, one after the other. This operator will take the value of the variable it is assigned and subtract one from it.

Third, you should understand that the expression in the parentheses of the while statement is run exactly like the expression in the if statement. The loop will continue to iterate as long as the expression in the parentheses evaluates to true.

Now that we understand all the new syntactical points about this script we can go back and explain what happens line by line.

  • Line 1: initialize the iterator to 1
  • Line 2: test to see if the expression is true
  • Line 3: if the expression is true we fall into the loop and evaluate the code (in this case we print the value of the iterator to the screen).
  • Line 4: we increment the iterator.

After this loop has been executed 10 times, the iterator will be incremented to 11. When the expression is tested again, it will evaluate to FALSE as 11 is not greater than or equal to 10 and the script will pickup at the end of the loop and run any remaining code in the script.

For Loops

for loops are much like while loops, except they are slightly more complex and as a result, more compact. The for loop expression is broken into 3 parts. Let's look at an example then break it down. I am going to write a loop that will accomplish the same thing our while loop example accomplished in the example above, we are just going to do it with a for loop instead this time.

for( $i = 0 ; $i <= 10 ; $i++ ) {
     echo $i . "<br />";
}

You can see how the expression of a for loop is broken into 3 segments by semicolons. Let's list each of those segments and define what they do.

  • $i = 0 This is what's called the initialization expression. This is the first statement that is executed when a for loop is run. Typically, the iterator variable is initialized in this expression.
  • $i <= 10 This is the test expression. This expression will be evaluated at the beginning of each loop cycle before the code in the braces is executed. If this expression evaluates to TRUE, the loop continues, if the expression evaluates to FALSE the loop closes.
  • $i++ This is the counter or iterator expression. It is run at the end of each loop cycle right before the test expression is tested for the next cycle. Most often, this expression simply contains an increment expression to the iterator. Just like this example shows.

There are other loops that we will probably touch on later in the series. Each of them has its strengths and weaknesses, and there are times when one is more appropriate than another, but they all do about the same thing, just in a slightly different way. There are no hard and fast rules as to which you should use when.

Conclusion

Hopefully you have learned something through reading this post; however, I would like to stress the fact that reading about programming will only get you so far. There is no better instructor than an error log full of mistakes in your code and things gone wrong in your script. You have to sit down and write your own code and try different things on your own to get to your full potential. As always, if you have any questions or comments, please leave the in the comments. I will be happy to help you out if I can.

 

Leave a Response

Use the <code> tag for code.

 

One Response to “PHP From the Top: 3 (Loops and Conditions)”

  1. [...] Continue reading here: PHP From the Top: 3 (Loops and Conditions) | 17 Webshop | Web … [...]