Learning PHP for WordPress Development: Control Flow Basics

PHP control flow basics

Welcome to this introduction to PHP control flow! This article continues our series explaining the basics of PHP for WordPress development.

Our discussion of control flow in PHP relies on a basic understanding of a couple of topics we’ve covered in earlier articles:

  1. PHP functions, which are one of the main forms of controlling the flow of execution of PHP code.
  2. PHP’s return statement, which is an important element of control flow inside PHP functions.

Now: What is control flow in PHP, and why is it worth discussing?

What PHP Control Flow Is

Control flow is what lets you write code that doesn’t always run.

“PHP control flow” sounds so awesome and technical that it can be easy to miss just how intuitive a concept it is.

In simple terms, control flow is what lets you write code that doesn’t always run. We don’t always want our PHP code to execute straight through, top-to-bottom, in the exact order it’s on the page, and control flow is what gives us an alternative to that.

If you’ve ever written (or wanted to write!) code that’s supposed to run only when someone publishes a new WordPress post, or only if the current user is logged in as an administrator, then you know how fundamental control flow is to PHP, WordPress, and indeed to any software system.

Control flow is the constant hum of “do-this-then-that” logic within programming.

Control flow is simply that constant hum of “do-this-then-that” logic within programming: “Do thing A, then do thing B, then do thing C over and over again a number of times determined by thing D, then maybe do thing E, but only if statement F is true.”

So that’s control flow. What is “PHP control flow?” Nothing special: it just refers to PHP’s particular ways of handling and implementing control flow itself.

As simple as it is, control flow is also hugely important: so important, in fact, that its presence or absence results in two completely distinct categories of technical languages. So if you want to know what makes PHP definitely a programming language (and HTML arguably not one), then this article’s for you. Let’s dive in!

Control Flow: A Simple Example

Before I get further, let’s look at a very basic example of PHP control flow at work:

<?php 

echo 'Hello.'; // Will print "Hello."

// Says "if 1 exactly equals 2, then run the code inside"
if ( 1 === 2 ) {
	// None of this code will ever run! It's inside a false if-statement.
	echo 'Good day.'; // This code will not run.
	echo 'Greetings.'; // Will not run.
	$year = date( 'Y' ); // Will not run.  
	echo $year; // Will not run.  
}

echo 'Hi again.' // Will print "Hi again."

Control flow causes code to run “only sometimes,” depending on particular circumstances that you specify.

From this quick example, we can see the essence of control flow: it causes code to run “only sometimes,” depending on particular circumstances that you, the programmer, specify. In the case of the code above, that “sometimes” is actually “never,” because our if-statement is set up to run only when 1 equals 2.

If any piece of the code above is confusing, don’t get too wrapped up in the details—there are lots more examples (containing much more useful code!) later on.

Control Flow and Language Types

As I mentioned, some technical languages have control flow and some don’t, and that makes for a huge difference in language type.

Specifically, whether or not a given technical language has control flow determines whether it is a:

  • Declarative language, like HTML or CSS, or an
  • Imperative language, like PHP or JavaScript.

In a declarative language, everything you write “shows up every time.” For example, the HTML you write into an .html file is what the browser will read and interpret: all of it, top to bottom, no two ways about it.

In an imperative language, you decide what parts of your code will be executed, and when.

In an imperative language, on the other hand, you decide what parts of your code will be executed, and under what circumstances.

For example, you could write a one-million-line PHP script that calculates the age of the universe. And then you could wrap that whole script in if( 1 === 2 ) { }, and none of those million lines of calculations will ever be performed at all, just as in the example above.

So we can definitely “write code” without control flow: for example, writing the HTML and CSS to describe how a static website should look. But when people talk about “writing in a programming language,” they often mean writing in an imperative language, because control flow—the ability to “do different things under different circumstances”—is central to so much of programming.

PHP Control Flow: Control Structures and Examples

In this section, we identify and explain the main control flow structures in PHP, with simple code examples.

Not Covered (Less Useful) PHP Control Structures

Right off the bat, we’ll do you a favor by not covering some PHP control flow structures that, honestly, I’ve never needed to use as a WordPress developer:

  • switch: Feels like it could be useful, but is also bulky and odd—and perhaps most useful in code that is also bulky and odd. Try refactoring first.
  • for()-loops: Confusing syntax. while() seems simpler and can do the same things.
  • declare(): Never heard of it before today, and I think I know why. It looks like a great way to write unpredictable code.

With those weird items out of the way, here are simple control flow examples in PHP:

if()-Statements

<?php 

$greeting = 'Hi';

// Says "if $greeting exactly equals the string 'Hi', then run the code inside"
if ( $greeting === 'Hi' ) {
	echo $greeting . '!';   // Will print out "Hi!"
}

// Says "if $greeting exactly equals the string 'Hello', then run the code inside"
if ( $greeting === 'Hello' ) {
	echo $greeting . ',';   // This code will not run
}

$greeting = 'Hello'; // $greeting is now "Hello"

if ( $greeting === 'Hi' ) {
	echo $greeting . '!';   // This code will not run
}

if ( $greeting === 'Hello' ) {
	echo $greeting . ',';   // Will print out "Hello,"
}

if()-Statements Including elseif()

It’s also possible to write the same logic above more clearly and efficiently, using elseif.

elseif is an operator that comes after an initial if-statement. The code inside an elseif will only run if both of two things are true:

  1. The initial if()-statement, and any following elseif()s that are above the current one, are all false.
  2. The elseif()‘s own condition is true.
<?php 

$greeting = 'Hi';

// Says "if $greeting exactly equals 'Hi', then run the code inside"
if ( $greeting === 'Hi' ) {
	echo $greeting . '!';   // Will print out "Hi!"
} 
// Says "If the above if()-statement was false,
// *and* $greeting exactly equals 'Hello', then run the code inside"
elseif ( $greeting === 'Hello' ) {
	echo $greeting . ',';   // This code will not run
}

$greeting = 'Hello'; // $greeting is now "Hello"

// Below is the same if-elseif block together
if ( $greeting === 'Hi' ) {
	echo $greeting . '!';   // This code will not run
} elseif ( $greeting === 'Hello' ) {
	echo $greeting . ',';   // Will print out "Hello,"
}

This code behaves exactly the same as the example above it, but it saves some lines. It also more clearly captures the truth that $greeting cannot be both “Hi” and “Hello” at the same time—so the “Hello” option really is clearest to think of as an elseif(), not as its own if()-statement about something totally separate.

while()-Loops

loop is a structure that can do something more than once. The main loops that are useful in PHP for WordPress are while() and foreach() loops.

Here’s a while()-loop in action:

$i = 0; // $i starts out at 0
// This while()-loop will keep running as long as $i is less than 3
while ( $i < 3 ) :
	echo 'Hello and $i is ' . $i . ' | ';
	$i++; // This means "increase $i by 1"
endwhile;

This loop will run a total of three times, printing out the following: Hello and $i is 0 | Hello and $i is 1 | Hello and $i is 2 | 

What happens on the fourth “loop” around? By this time, $i is actually equal to 3, which is not less than 3. The while()-loop’s condition is no longer true, so the loop stops.

Side Note on PHP Alternate Syntax

By the way, please notice that the above example uses alternate syntax: instead of while () { }, it says while () : endwhile. The truth is that those two things mean exactly the same thing in PHP: they’re alternate syntax (“way of expressing”) for the same underlying logic.

Pretty much any of the PHP control structures in this article can be written two ways:

while () { } or while () : endwhile;

if () { } or if () : endif;

foreach () { } or foreach () : endforeach;

And so on. These structures behave identically, so which style of writing you choose is a matter of preference and of which coding standards you follow. The biggest thing is that it’s good to be consistent in using whichever syntax you choose.

Learn to Avoid Infinite Loops

If you ever want to break PHP—and make your or your client’s website unusable—then run an infinite loop:

$i = 0; // $i starts out at 0
// This while()-loop will keep running as long as $i is less than 3
while ( $i < 3 ) :
	echo 'oh no ';
endwhile;

This loop will run forever, printing out oh no oh no oh no oh no oh no oh no oh no oh no oh no oh no oh no  until your server finally decides it’s had enough and times out.

What changed from the example before it? We no longer have the $i++; line that grows $i by 1 every time the loop runs. $i stays stuck at 0, which is always less than three, so the loop never stops. Your loops always need a reason to stop.

foreach()-Loops

A PHP foreach() loop is an operation that works with one specific data type: arrays. What foreach() does is “the same thing, once, for each and every element in the array it’s given.” Let’s see an example:

<?php

$shopping_list = array( 'milk', 'eggs', 'chocolate' ); 

foreach( $shopping_list as $item ) {
	echo 'I need ' . $item . '! ';
} 
?>

The example above will print out the following: I need milk! I need eggs! I need chocolate! 

There are more complicated uses of foreach() that work with associative arrays (arrays with more complex structures), but we’re going to leave those for later.

PHP Functions

As we discussed in our article on PHP functions, the whole point of a function is that it doesn’t run right away. We didn’t mention this at the time, but that’s actually a statement about control flow.

Let’s take another look at our most basic function example from that article:

<?php

// This function won't run yet
function say_hello() {
	echo 'Hello world!';
}

// It still won't run yet
$var = 100;

// Now it'll run
say_hello(); // Will print "Hello world!"

?>

Functions are the best way of only invoking bits of logic whenever needed, and are as basic to PHP control flow as any of the other language constructs listed here.

return and Control Flow

As we covered in our full article on PHP’s return statement, return will stop execution of a function—and hand back whatever it’s told to. This is an important element of control flow.

<?php

function multiply( $num1, $num2 ) {
	return $num1 * $num2;
	
	echo 'Bananas'; // Won't run! Function already returned
}

echo multiply( 4, 5 ); // Will print out "20"

So within a function, return is a “hard stop,” and, generally, a “hand back your work.”

exit and die

These two statements are alternate syntax for one another—they do the same thing. What they do is to stop all PHP script execution dead in its tracks.

<?php

echo "I don't feel so good..."; // Will print "I don't feel so good..."

die;

$var = 100; // It's already dead! This code will not run.

var_dump( date( 'm Y' ) ); // Will not run x__x

return 1234567890; // Will not run x__x

?>

This sounds like a heavy-duty thing to do, but it can be very important, for example in writing Ajax functions. With var_dump(), die() is also super-useful in debugging.

You can actually pass in an argument into die() to print something to the page in the process, but let’s leave the details of that for now.

Now You Know Flow!

Together, the control structures above are our tools for telling PHP “what to do, when.” That ability is the major distinction between an imperative language like PHP (which is definitely a “programming language” no matter who you ask) and a declarative language like HTML (which smug people will sometimes say isn’t really a “programming language,” although that’s a matter of semantics).

If the PHP control structures and the simple control flow examples above are making some sense to you, then you’re well on your way to being able to navigate the real PHP code you’ll encounter as a working WordPress developer.

Thanks for reading! We’d love to hear any questions or thoughts, either in the comments below or in our Facebook group.


3 Responses

Comments

Add a Comment

Your email address will not be published. Required fields are marked *