Getting Started with PHP: Part 3 - Program Control Structures

In the last part of this series, we learned about using variables in PHP. Today, we will learn about using program control structures, such as if/else blocks and for/while loops. There are a number of other control structures, but these are the most common, and can accomplish everything that the other ones can.

Conditional Execution Using an If/Else Block

There are many circumstances where we would want to execute a certain block of code only if some other condition were true. In times like this, we want to make use of an if/else block. Let’s see how we could use this method to display one message for all visitors that came from digg, and a different message for everyone else:

<?php
if (stristr($_SERVER["HTTP_REFERER"], “http://digg.com”) === TRUE) {
  echo “Greetings digg users!”;
}
else {
  echo “Welcome to my website!”;
}
?>

Let’s take a closer look at exactly what is going on here. $_SERVER["HTTP_REFERER"] is a built-in server variable that contains the referring website, if there is one. The function stristr searches for one string within another string. In this case, we are searching for “http://digg.com” within the referrer contained in $_SERVER["HTTP_REFERER"]. If “http://digg.com” is found within the referrer string, then stristr will return TRUE, so this is the condition that we check for in our if statement. The code that we want to execute when this occurs follows the if statement, contained within curly braces {}. If the statement evaluates to FALSE, then the code that follows our else statement will be executed (also contained within curly braces). If we had not wanted to display a default message, we could have simply left off the else statement altogether.

If we had multiple conditions to test, we could have used the elseif statement. Let’s look at a simple example of how this could be used:

<?php
$gradePercent = 75;
if ($gradePercent > 90) {
  echo "You got an A!";
}
elseif ($gradePercent > 80) {
  echo "You got a B!";
}
elseif ($gradePercent > 70) {
  echo "You got a C!";
}
elseif ($gradePercent > 60) {
  echo "You got a D!";
}
else {
  echo "You got an F!";
}
?>

Using For/While Loops

On some occasions, you will need to loop through a list of values - to list your 5 most recent blog posts, for example. You have several different choices of loops to use, depending on your exact situation. The 2 most popular loop structures that I will cover are for and while loops. The while loop is a bit simpler, so I will cover that one first:

<?php
$count = 1;
while ($count <= 10) {
  echo "$count ";
  $count++;
}
?>

The conditional statement in the while loop says that the loop will be executed as long as $count is less than or equal to 10. Inside of the loop, we just print out the current value of our variable $count, and then increment $count by 1 ($count++ is a shorthand statement that is equivalent to $count = $count + 1). Note that all the steps we want to perform inside of our loop are contained within curly braces, just as we did with the if/else statements above. The result of this loop would be to print the numbers 1 through 10 on the screen.

Now let’s take a look at how we would do the same thing with a for loop:

<?php
for ($count = 1; $count <= 10; $count++) {
  echo "$count ";
}
?>

You will notice that the for statement is a bit more complicated than the while loop, but it also does a lot more for us. There are 3 parts that must be included in a for statement, separated by semi-colons: the first initializes our loop counter, the 2nd is the exit condition, and the 3rd increments the loop counter after each pass through the loop. One reason I like the for loop is that it forces me to remember to increment the loop counter, whereas the while loop does not. If you forget to increment the loop counter, the exit condition will never be satisfied, resulting in an infinite loop!

For Next Time

Now that you have learned about using if/else blocks and for/while loops, you can really start to write some interesting programs in PHP. For the next part in this series, I would love to get some feedback on what you’d like to hear about next. Do you want to learn about creating your own functions, or how about database access? I’m wide open to suggestions, so leave ‘em here in the comments, and tell me what you’d like to learn about next.

You can already read Getting Started with PHP: Part 4 - Integrating PHP and HTML.

You can receive our articles for free on your email inbox, with more tech and web news, funny games and interesting links. Just enter your email below:

13 Responses to “Getting Started with PHP: Part 3 - Program Control Structures”

  1. Mike Smith on December 10th, 2007 3:09 pm

    I like the code for the “welcome digg users”. I’m going to have to try that on my blog for stumbleupon users since I get a lot of traffic from there.

    Thanks for posting these php articles. They’re useful, and easy to follow.

  2. Brandon on December 10th, 2007 4:04 pm

    No problem Mike, I’m happy to hear that they have been useful to you.

  3. Dana Mark on December 10th, 2007 4:15 pm

    Thanks for your helpful startup articles on PHP. Eventually I would like to see some specific help on integrating PHP with HTML. For now, database access would be helpful. Thanks for your good work!

  4. Travis on December 10th, 2007 7:40 pm

    Hey Brandon, you might want to mention the alternative form of “if .. then”, etc in a future post:

    The condition was true!

    Anyone reading this who wants to modify projects such as Wordpress would probably find that info quite useful!

  5. Travis on December 10th, 2007 7:42 pm

    oops!… my code was stripped in the comment.

    I was talk about “if ( condition ): ” and “endif;”

  6. Daniel on December 10th, 2007 7:59 pm

    Yeah a bit of PHP dedicated to Wordpress would be cool, I will give Brandon a heads up.

    Thanks Travis

  7. Mike Smith on December 10th, 2007 10:27 pm

    Travis,

    So, if I wanted to add this to my wordpress posts, how would I go about doing that? Sorry, I haven’t had much luck with this stuff yet and don’t want to test this out over and over again while I’m building traffic to my site and something break in the code. :)

    Thanks,
    Mike

  8. Daniel on December 10th, 2007 10:45 pm

    Mike, if you are inserting php code in the php pages you should be fine. If, on the other hand, you want to add some php code inside pages and posts you will need to grab a plugin to enable code on these places.

    This is what I use:
    http://www.nosq.com/blog/2006/.....wordpress/

  9. Brandon on December 10th, 2007 11:33 pm

    @Travis - Yes, that’s a great idea, I’ll try to include it in a future post (I had actually thought about including it in this one, but didn’t want this article to be too long).

  10. Nathaniel on December 11th, 2007 6:04 am

    I like this little series. Although I already knew everything that you’ve stated so far, you’ve gotten to the point to where the majority of people could easily take this information and produce a wide variety of applications and dynamic pages.

    There are several directions to go next… Let me think… perhaps queries? Passing variables? Databaise access? After all of those, we could pretty much do anything. After that, it’s all advanced stuff.

    Nice work. You present the information very well. I look forward to reading more.

  11. Brandon on December 11th, 2007 4:14 pm

    Thanks for the input Nathaniel. With the feedback I’ve received on this post so far, I’m leaning toward either PHP and HTML integration, or database access for the next part in the series.

  1. Getting Started with PHP: Part 2 - Variables
  2. Getting Started with PHP: Part 4 - Integrating PHP and HTML

Got something to say?





Sponsors

Premium WordPress Themes Online Invoicing For Freelancers Why I recommend Doreo Hosting Maximize Your Rankings Smarter Blogging

Popular Articles

Recent Articles