PHP control structures are something you will encounter frequently when working with WordPress. In this article I give a short overview of the available controls followed by common WP examples.

Control Structures

Any PHP script is built out of a series of statements. A statement can be an assignment, a function call, a loop, a conditional statement or even a statement that does nothing (an empty statement).

PHP Manual

Require & Include

include: includes and evaluates the specified file.

include_once: almost identical to include, but will check if the file has already been included, and if so, not include it again.

require and require_once: almost identical to include and include_once but produce a fatal error upon failure.

If & Else

if: a vital part of writing code, the If construct allows for conditional execution of code fragments.

else: extends an if statement to excute code fragements when the If condition is not met.

elseif: a combination of if and else, it will execute code when the If statement is not met and another condition is met.

if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}

Alternative Syntax: PHP offers an alternative syntax for If, While, For, Foreach and Switch. Instead of curly brackets, the syntax uses colons and end statements:

<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

Coding Standards: WordPress specifies brace style but this only means that single-statement inline control structures are prohibited. Use of the alternative syntax is allowed, especially in templates where PHP code is embeded within HTML.

Switch

switch: is similar to a series of IF statements on the same expression.

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    default:
       echo "i is not equal to 0 or 1";
}

Loops

while: this is the simplest way to create a loop with a statement being exectured for as long as the condition is met.

do-while: very similar to while, the expression is checked at the end.

for: the most complex loops. The 1st expression is executed once, the 2nd expression is then evaluated and as long as it’s met, the 3rd expression is executed at the end of each iteration.

/* This example will display the numbers 1 through 10: */

for ($i = 1; $i <= 10; $i++) {
    echo $i;
}

foreach: provides an easy way to iterate over arrays. Only works with arrays and objects. Other data types result in an error.

foreach ($a as $v) {
    // do something 
}

/* can also make use of the array keys */
foreach ($a as $k => $v) {
   // do something 
}

Break & continue

break: ends execution of the current For, Foreach, While, Do-While and Switch Structure.

continue: is used within looping structures to skip the rest of the current loop iteration.

/* The following shows the difference between coninue and loop
when used within Foreach */

$stack = array('first', 'second', 'third', 'fourth', 'fifth');

foreach($stack AS $v){
    if($v == 'second')continue;
    if($v == 'fourth')break;
    echo $v.'<br>';
}

/*
first 
third 
*/

Match (PHP 8)

The match expression branches evaluation based on an identity check of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==). Match expressions are available as of PHP 8.0.0.

PHP Handbook

Coding Standards: WP 5.9 currently has beta support for PHP 8, so use with caution.

<?php
$food = 'cake';

$return_value = match ($food) {
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => 'This food is a cake',
};

var_dump($return_value);
?>

The above example will output:

string(19) "This food is a cake"

The match expression is similar to a switch statement but has some key differences:

  • A match arm compares values strictly (===) instead of loosely as the switch statement does.
  • A match expression returns a value.
  • match arms do not fall-through to later cases the way switch statements do.
  • A match expression must be exhaustive.

Coding Examples

Archive.php

Archive.php usually contains an If / Else statement to check if posts exist. If yes, the posts are shown, if not, the template for “nothing found” is shown. The following example is adapted from Storefront, the theme by the WooCommerce team, as products are simply custom post types and use the same code as the default WP loop:

/* Example from archive.php in Storefront theme */

if ( have_posts() ) : 
		get_template_part( 'loop' );
else :
		get_template_part( 'content', 'none' );
endif;

The above code references the template for loop which contains the While statement the iterates over all found products:

/* Example from the loop.php template in Storefront */

while ( have_posts() ) :
	the_post();
	get_template_part( 'content', get_post_format() );
endwhile;

In WooCommerce, the above code will output all the products relevant to the page, either within a category or the shop page.

To further understand the WP loop see The Loop within the Codex or take a look at The Loop in Action.

Leave a Reply

Your email address will not be published.