Skip to content

Learning PHP for WordPress Development: Understanding PHP’s return

Welcome to this rundown on return in PHP! This article continues our series explaining the basics of PHP for WordPress development.

Our discussion of PHP’s return builds on two topics we’ve covered in earlier articles:

  1. PHP functions. Functions are where return is useful, so you’ll want to understand the basics of what PHP functions are and what they do.
  2. PHP’s echo. echo is how PHP outputs things to the page, and it and return are flip sides of a coin—so, again, you should understand the basics of how it operates moving into our exploration of return.

Now: Here’s how return works in PHP, and why it’s super-powerful.

In PHP, return is How a Function “Gives Back” its Results

Let’s start by understanding why we need return in the first place.

PHP Usually echos to the Page Eventually, But It Does Lots More Too

PHP certainly isn’t echoing out to the page the whole time.

As we covered with echo, the final purpose of most PHP is to output markup into the HTML document that the user sees in her browser. For very simple uses of PHP, it really can be just an “HTML convenience tool,” to do things like give HTML elements sequential IDs.

However, looking at PHP that way risks making it sound way simpler than it is. In WordPress and most other PHP systems, a single line of outputted markup—“You are now logged in! Your last login was three weeks and two days ago.”—might reflect literally thousands of calculations across dozens of PHP files totaling megabytes of code.

In other words, PHP certainly isn’t echoing out to the page the whole time. In most PHP applications, data is being passed around and worked on extensively before it ever “exits through the front door” in the form of an echo statement.

Functions Need to Talk to Each Other

In our article introducing PHP functions, we made a few key points, which we’ll summarize here:

  1. PHP functions are defined, repeatable “bits of work.” Having these clear, separate “bits of work” is what keeps PHP code from mushing together into a repetitive, unworkable glue.
  2. It’s possible to give a PHP function data to work with, by passing that data into the function. For the technical details refer to the article, but the main point is that a function can be “given” data to work with, and that it will do so in whatever way the function itself is written to work.

This brings us to our next question: What should a PHP function do with the data it’s given, once it’s done working on it? To echo it directly to the page is one possibility—but definitely not the most common one.

return is how a function passes back its results—to whatever piece of code called it—for further use.

Far more often, you want to “hand back” the result. That is, you want to pass the worked-on data back to the rest of your PHP application, to be worked on further.

This is what return does. In PHP and many other programming languages, return is how a function passes back its results to whatever piece of code “called” (invoked) it, where it can further worked with and used.

Code Demo: How PHP Uses return to Pass Back a Function’s Results

Okay, enough fancy paragraphs. Let’s understand return by diving in and looking at a code example, which revolves around two functions:

  1. echo_text(), which echos (prints) text directly.
  2. return_text(), which doesn’t print anything, but returns its results for further use.

Here’s the demo:

<?php

function echo_text() {
	echo 'Kittens.';
}

echo_text(); // Will print "Kittens."

$var1 = echo_text(); // Bad code. Will print "Kittens." and won't set a value for $var1.

echo $var1; // Problem. $var1 was never set, because echo_text() echos instead of returning.

function return_text() {
	return 'Puppies.';
}

$var2 = return_text(); // $var2 now has value "Puppies."

echo $var2; // Will print "Puppies." since that's the value of $var2.

echo return_text(); // Will print "Puppies." Works by getting the returned value, and immediately echoing it.

return_text(); // Bad code, does nothing. return_text() runs and returns "Puppies." but the returned value isn't used for anything.

?>

Hopefully that example starts to illustrate how return works, and what makes it a complement to echo: rather than printing a function’s results out onto the page, return takes those results and gives them back to whatever operation it was that called the function—whether that operation was defining a variable, an echo statement, or anything else.

Code Demo: Using return to Pass Back Different Kinds of Data

Our return_text() function, above, is pretty silly: it always returns the same thing, the string “Puppies.” In reality, for it to be useful, return will almost always be returning dynamically calculated values, and these values can be of any PHP data type: string, ineger, array, object, and more. Let’s see a few examples in action:

<?php

function return_the_number_five() {
	return 5;
}

$var1 = 3 * return_the_number_five(); // $var1 now has value 15.

function multiply( $num1, $num2 ) {
	return $num1 * $num2;
}

$var2 = multiply( 3, 10 ); // $var2 now has value 30.

$var3 = multiply( 8, return_the_number_five() ); // $var3 now has value 40.
// This example demonstrates calling one function to get its return value, and passing that value in as an argument of another function: return_the_number_five() "becomes" its return value, 5, which is then passed into multiply().

function get_my_shopping_list() {
	return array( 'plums', 'toothpaste' );
}

$my_list = get_my_shopping_list(); // $my_list is now an array with values [ 'plums', 'toothpaste' ]
echo $list[0]; // Will print "plums"

function add_to_shopping_list( $list, $item ) {
	$list[] = $item; // This means "add $item to the end of array $list"
	return $list;
}

$my_bigger_list = add_to_shopping_list( get_my_shopping_list(), 'ice cream' );
// $my_bigger_list is now an array with values [ 'plums', 'toothpaste', 'ice cream' ]

$my_bigger_list = add_to_shopping_list( $my_bigger_list, 'shampoo' );
// $my_bigger_list is now an array with values [ 'plums', 'toothpaste', 'ice cream', 'shampoo' ]
// You can pass a variable into a function and have that function's return value change the variable
?>

If you’ve understand the examples above, you’ve got a good handle on return. The pattern is the same: you call a function, get its return value, and do something with it.

The way I think about return is that the function “becomes” its return value everywhere it’s called.

Thinking with my fuzzy human brain, the way I think about return is that the function “becomes” its return value everywhere it’s called. For example,return_the_number_five() above becomes 5 anytime it’s called—whether it’s called in the process of echoing something, defining a variable, or even as an argument for another function.

return and WordPress: Template Tag Naming

As in any PHP application, WordPress uses return absolutely all the time. So return is “relevant” to WordPress in the same way that breathing is “relevant” to baseball: it’s impossible to imagine the second without the first.

However, there is a particular part of WordPress’s codebase where, once you understand echo, return, and their “two sides of a coin”-type relationship, the whole thing lights up all at once. The topic is WordPress’s post template tags, and specifically their the_() and get_the_() function naming convention, and it’s one of the super-satisfying areas in which WordPress’s function library mirrors the structure of PHP itself.

Have you ever wondered the difference between the_ID() and get_the_ID()? It’s as simple as this:

<?php

// WordPress's get_the_ID() function
function get_the_ID() {
	$post = get_post(); // Get the current post
	return ! empty$post ) ? $post->ID : false; // Return the current post's ID, or false if none
}

// WordPress's the_ID() function
function the_ID() {
	echo get_the_ID(); // Call get_the_ID() and echo the returned result - simple as that
}

?>

So the difference between the_() and get_the_() is simply the difference between echo and return. This holds true for functions like the_content()/get_the_content(), the_title()/get_the_title(), and so on—and it simply boils down to echoing results or returning them for further use.

For more on these template tag functions, have a look at our full article on the topic:

WordPress Template Tags: How They Show Post Content & More

return to Learning PHP

The echo and return dichotomy, and the ways those two language constructs work together, form a bedrock piece of understanding that PHP knowledge is built on. This dichotomy also ties nicely into a helpful naming convention within WordPress’s template tags, which is one of the cleanest and easiest-to-use pieces of the WordPress codebase.

More broadly, “return values”—the way that functions give stuff back—are a concept that virtually no modern programming language would make any sense without. They’re very much at the heart of programming itself.

In other words, the time you’ve spent learning this should earn you a hefty—well, return.

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

Yay! 🎉 You made it to the end of the article!
Fred Meyer
Share:

0 Comments
Inline Feedbacks
View all comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!