5.5: Control Structures

Section 5.5 PHP Control Structures

  • What do we mean by control structures? Control structures are found in all computer programs. As a program is executing its instructions there will be needs to processing a collection of data iteratively. We use one of PHP's various loops for this purpose. Most programs also have code that tests the condition of some data and then branches off to process additional statements based on the condition tested. In this section we will learn about PHP's conditional logic constructs and a variety of ways we can loop through a list of data and render it to the screen.

  • Before we discuss the conditional logic and looping constructs in PHP let's take a moment to consider a common task that all of us (hopefully) do that involves the some of the conditional logic and looping concepts we are about to discuss. Consider washing your hair. Most of us don't bother reading the directions on the bottle because we pretty much have this task down and can even do it blind-folded. Let's pretend for a moment that we want to consult the directions. What do we find on the bottles of shampoo and conditioner?

Maximum Big Hair Shampoo (great for that eighties rock-n-roll look)

  1. Wet hair

  2. Apply 2 ounces of Maximum Big Hair Shampoo to hair

  3. Lather briskly

  4. Rinse

  5. If hair is not clean repeat this process

Maximum Big Hair Conditioner (great for that eighties rock-n-roll look)

  1. Start with clean, wet hair

  2. Apply 2 ounces of Maximum Big Hair Conditioner to hair

  3. Wait one minute

  4. Rinse

As you can see, we are already old pro's at conditional and looping logic! Now let's see how these concepts are implemented in PHP

Further information and examples of using the PHP Control Structures

5.5.1 PHP Conditional Logic

The "if" statement is one of the most important logic constructs in programming. We use the "if" statement to test some value and then based on the result the program branches to one set of PHP statements or another. Let's look at some examples Simple If statement

<?php
$theColor = "crimson"; 

If($theColor = = "crimson"){
    echo "hello there I am crimson";
}
?>
  • Simple if-else statement

<?php
$theColor = "crimson";

If($theColor = = "crimson"){
    echo "hello there I am crimson" ;
}
?>
  • Compound if-else statement

<?php
$theColor = "purple";    

If($theColor = = "crimson"){
        echo "I am crimson" ;
    }
elseif($theColor == "purple"){
        echo "I am purple";
    }
elseif($theColor == "green"){
        echo "I am green";
    }
else{"Please assign a color";
    }
?>
  • Switch statement

    • The switch statement is an efficient and easily understood conditional control structure.

    • The switch statement is typically used when the use of nested if-elseif statements will be deeply nested.

    • Additionally, a switch statement only makes a single evaluation while and if-elseif must test as each condition fails.

  • It is necessary to understand how the switch statement actually executes or you will end up with mistakes, usually what is called a "fall through" where code continues to execute when it should have branched or stopped.

  • The switch statement executes line-by-line. When a case statement is found that matches the value of the variable being evaluated PHP begins executing statements and will keep executing line by line until it arrives at the end of the switch statement or PHP encounters a break statement that branches out of the switch statement to the next line of code after the switch statement. So it is very important to include the break to exit the switch statement once your condition is found and the necessary statements are executed.

  • The default statement is not mandatory but considered good practice. The default statement will execute if PHP does not encounter a matching case value

<?php
$theColor = "crimson";
$theMessage ="";

switch ($theColor) {
    case "blue":
        $theMessage = "I am blue";
        break;
    case "green":
          $theMessage = "I am green";
        break;
    case "crimson":
          $theMessage = "I am crimson";
        break;
    default:
        $theMessage = "Please assign a color";
}
echo $theMessage;
?>
  • 5.5.2 PHP for loops

    • Use a for loop if you know in advance how many times you need to loop.

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The loop is at number: $x";
}
?>
  • Result:

    • The number is: 0

    • The number is: 1

    • The number is: 2

    • The number is: 3

    • The number is: 4

    • The number is: 5

    • The number is: 6

    • The number is: 7

    • The number is: 8

    • The number is: 9

    • The number is: 10

  • The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. In some programming languages this is called an enhanced for loop.

<?php
$shapes = array("square", "circle", "ellipse", "triangle", 
"dodecahedron", "whatchamacallit");
    foreach ($shapes as $value) {
echo "$value";
}
?>
  • Result:

    • square

    • circle

    • ellipse

    • triangle

    • dodecahedron

    • whatchamacallit

  • 5.5.3 PHP While Loops

    • The while loop executes a block of code as long as a specified condition is true. It is possible that if the condition is true when entering the loop that it will not run at all.

<?php
$shapes = array("square", "circle", "elipse", "triangle", "rectangle", "dodecahedron");
$count = 0;</b> 
while($count < count($shapes)){
echo "this is your shape $shapes[$count] <br/>";
$count++;
}
?>
  • Result:

    • this is your shape of the day: square

    • this is your shape of the day: circle

    • this is your shape of the day: ellipse

    • this is your shape of the day: triangle

    • this is your shape of the day: rectangle

    • this is your shape of the day: dodecahedron

  • The do...while loop will always execute the block of code once, it will then check the condition, and repeat the loop while the specified condition is true.

<?php
$shapes = array("square", "circle", "ellipse", "triangle", "rectangle", "dodecahedron");
$count = 0;
do{
echo "this is your shape of the day: $shapes[$count] <br/>";
$count++;
}while($count < count($shapes))
?>
  • Result:

    • this is your shape of the day: square

    • this is your shape of the day: circle

    • this is your shape of the day: ellipse

    • this is your shape of the day: triangle

    • this is your shape of the day: rectangle

    • this is your shape of the day: dodecahedron

  • We are going to create a PHP while loop that will cycle through and display all of the blog posts for the site. Since we do not yet have any blog posts lets add some using the Diamond Dog Entertainment administration portal

  • Open the Diamond Dog Entertainment dashboard. See the address line of the browser in Figure 5.5.1

Figure 5.5.1

  • Once the address is entered in the browser address box press enter

  • The site's admin portal will open and look like this:

Figure 5.5.2

  • Click on the right-hand menu item labeled "Posts" and we will see a work area that shows us the blog posts we currently have in the site library and also a place to edit or create a new blog post.

  • Click the Add New button and then click the "Publish" button. Enter only the Title and the blog content. Do not concern yourself with other features such as adding media at this time. You can enter anything you like or go to the lorem ipsum generator to create a couple of paragraphs of lorem ipsum and past it into the text area. Repeat this process to create three or four blogs so that we have data to work with on our index page.

Figure 5.5.3

  • In this section we will start using WordPress Library Functions with our PHP. We are fortunate in that WordPress provides a library rich in functionality that allows us to create WordPress sites with minimum coding. Let's take a look at an essential reference for creating WordPress sites with PHP.

Figure 5.5.4

  • The WordPress Developer Reference has much to offer. There are hundreds of functions, classes and methods already pre-built and ready for use.

  • Let's take a few minutes to explore what this reference site has to offer us.

Figure 5.5.5

  • Let's apply what we have learned about loops and write some code that will loop and display the blog posts we have entered.

  • PHP loops allow us to loop for a specific number of times based on a counting limit or until a specific condition is reached.

  • We will start with the While loop since we have an immediate need for this PHP construct in our next exercise. Open your text editor, return to the index.php page and enter the following code:

1. <?php get_header(); ?>
2. <div class="container container--narrow page-section">
3. <?php
4. while(have_posts()) {
5. the_post(); ?>
6. <div class="post-item">
7. <div class="generic-content">
8. <?php get_template_part( 'template-parts/post/content', get_post_format() ); ?>
9. </div>
10. </div>
11. <?php }
12. echo paginate_links();
13. ?>
14. </div>
15. <?php get_footer(); ?>

Figure 5.5.6

  • This code will present the viewer with a list of Blog posts. Let's step through this code fragment line-by-line

    1. <?php get_header(); ?> Opens PHP and requests the header.php file be pre-pended to this code then closes PHP.

    2. A <div> container that holds the entire Blog roll. The container ends on line 13 with the </div> tag.

    3. <?php is an open PHP tag which we have seen before

    4. While(have_posts()){ is the beginning of the loop that will cycle through each of the Blog posts we created. Note that have_posts() is a WordPress library function that is provided to developers. That { curly bracket tells the server that all of the PHP statements from this point until a } right curly bracket is encountered belong together inside the loop.

    5. the_post(); ?> is another WordPress library function that iterates the Blog post index. Note the semi-colon required at the end of every PHP statement in our code. The ?> is used to tell the server we are finished processing PHP for the moment.

    6. <div class="post-item> is a container for all code between line 5 and 17 where the end </div> tag is found. The "post-item" class is a style from our style sheet and that style is applied to everything rendered from line 5 to line 10.

    7. <div class="generic-content"> sets up another container and applies the desired style.

    8. <?php get_template_part( 'template-parts/post/content', get_post_format() ); ?>

    9. The PHP open tag signals the server that what follows is PHP code.

    10. get_template_part('template-parts/post/content', tells PHP that the content.php template found in the parent theme will be used to format the data

    11. The data that is passed to the content.php is retrieved using the get_post_format() WordPress library function.

    12. </div> closes the container started on line 7.

    13. </div> closes the container started on line 6.

    14. <?php opens PHP to signal the server that php code will follow.

    15. echo paginate_links(); echo renders the result from the paginate_links() WordPress library function.

    16. ?> closes PHP to signal the server that HTML follows.

    17. </div> closes the container opened at line 2

    18. <?php get_footer(); ?> opens PHP to signal the server that PHP code follows. get_footer(); tells PHP to append the footer.php template to this page. Permalinks are the permanent URLs to your individual pages and blog posts, as well as your category and tag archives. A permalink is the web address used to link to your content. The URL to each post should be permanent, and never change — hence the name permalink.

Last updated