Learning PHP for WordPress Development: Understanding PHP’s echo

Welcome to this rundown on echo in PHP! This article is part of our series explaining the fundamentals of PHP for WordPress development, so that you can start learning the language of WordPress “under the hood” and unlock the powers of a full-fledged WordPress developer.

To understand PHP’s echo, it’s helpful to have two core concepts in mind:

  1. PHP’s main function is to output HTML. Almost every action PHP performs ends up with it outputting HTML onto a webpage for users to see.
  2. echo is PHP’s main way of actually outputting HTML. Most PHP operations end, ultimately, with echoing a string of HTML markup.

We’ll explain these core concepts in sequence, and give ample code demos to show how PHP’s echo actually works.

PHP Outputs HTML, and echo is How It Does So

I find that PHP tutorials often overlook explaining, step-by-step, how PHP changes its broader software environment. In other words, a beginner tutorial should not just say “great, now we print the result to the page with PHP”: it should explain what that actually means.

For that conversation, it’s helpful to know the basics of the software environment (most commonly LAMP) that PHP runs in. And it’s especially helpful to know the difference between “server-side” and “client-side,” to the point where the phrase “PHP is a server-side programming language” has meaning. Please give both those links a skim if you find yourself wanting more context for the rest of this section.

Now: Here’s a detailed, sequential demo that explains both what it actually means to say that “PHP outputs HTML,” and to say that “echo is how PHP outputs HTML.”

Code Demo: How PHP Uses echo to Output HTML

We’ll start this demo with a code example that is pure HTML, no PHP at all.

<html>
<head></head>
<body>
<h1>Hi, I'm pure HTML.</h1>
</body>
</html>

Now, let’s pretend that we wrote the code above into a text editor (such as Notepad), and saved the whole thing as a file, let’s say example.html.

If we then upload example.html to the web server that the wpshout.com domain points to, we can do something cool: we can open our web browser, visit wpshout.com/example.html, and see the text “Hi, I’m pure HTML.” in a nice big header on an otherwise blank page.

In this dead-simple example, what is the “outputted HTML” we’re talking about? It’s not only the phrase “Hi, I’m pure HTML.” itself, but it’s more than that: It’s all the HTML markup that the web server sends to your browser for your browser to be able to generate the page we’re looking at. Let’s use Google Chrome’s “Inspect Element” tool to see that markup itself:

HTML browser output example inspect element

So our outputted markup is not just words: it’s also HTML tags like <html> and <h1> that structure and change what appears on the page. And what do we mean by “the page”? We mean the webpage: the screenful of words and other things that your browser shows you when you visit this URL.

Now, what would happen if we were to change our example.html file to be named example.php, while keeping its contents the same? The answer is simple: other than a URL change, nothing would happen.

HTML in PHP file browser example

That teaches us something important: it’s fine for .php files to be just pure HTML, with no actual PHP in them. This is because PHP outputs HTML anyway: all we’re doing is skipping the step of writing PHP in the first place.

However, if we do want to write PHP at any point, we will have to be working in a .php file. By default, PHP can’t run in a .html file.

Now for the good part: let’s put actual PHP into example.php, to show you what PHP’s echo can do:

<html>
<head></head>
<body>
<h1>Hi, I'm <?php echo '<em>DEFINITELY NOT!</em>'; ?> pure HTML.</h1> 
</body>
</html>

With this new mixture of HTML and PHP, the markup that’s outputted to the page is going to change significantly:

PHP output HTML example

Do you see what happened there? The PHP that we echoed got “consumed” to generate pure, clean HTML. Your browser doesn’t deal with <?php tags—in fact, it can’t. PHP is a purely server-side language: all your PHP must get processed into HTML before it’s sent to your browser.

And did you see how echo outputs not only text content, but rather HTML markup? In other words, our echo contained both regular words, and an HTML <em> tag to surround them and make them italic. When we tell PHP to echo those things, they both get printed straight onto the (web)page as pure HTML, and the result is two words of italicized text.

If you’ve understood the code and screenshots above—and how that code makes it from a .php file into HTML markup in your browser—then you understand the fundamentals of PHP’s echo. And again, a main thing to understand is that you’d be seeing these examples inside a .php file, and that the way to make the examples come to life and “do something” is to access that file in your web browser.

The rest of this article digs deeper into echo, and especially into how it interacts with PHP’s data types, as well as providing further demo examples and a few fine points to keep in mind.

echo Only Handles Strings!

One main thing to understand is that echo is always expecting a string: a sequence of letters, numbers, and symbols.

All HTML markup is a string: in other words, HTML is just a sequence of letters, numbers, and symbols. HTML is a markup language—so named because it’s, at its core, a way of “marking up” a text manuscript so that a web browser can display it in a special way.

PHP, on the other hand, is a full-fledged programming language, and “string” is only one of its many data types: others include int, boolean, array, object, and more.

These data types capture various concepts that a string—a “manuscript-like” sequence of letters, numbers, and symbols—cannot. For example, a boolean captures the concepts of true and false themselves. An int captures an integer number, with no decimal points. An array captures a list of similar items. And so on.

How do you know if you’re working with a string in PHP? The presence or absence of quotes, either single ' or double " quotes.

<?php

$var1 = 'Hi'; // $var1 is of type string, string is "Hi"

$var2 = "Hi"; // $var2 is of type string, string is "Hi"

$var3 = "Hi'; // Uh-oh, now you broke something. Quote types must match

$var4 = '123'; // $var4 is of type string, string is "123"

$var5 = 123; // $var5 is of type int, integer is 123

$var6 = "true"; // $var6 if of type string, string is "true"

$var7 = true; // $var7 is of type boolean, boolean value is true

$var8 = '<div>ABC123!@#</div> $arr = new array(); return 100 * 999';
// $var8 is of type string,
// string value is all the stuff between the two ' characters

?>

So strings are built with quotes inside PHP. And strings are what echo wants: it wants to output an HTML manuscript, so if you give it a manuscript to work with, it’ll be happy. If not, your results may vary. Let’s take a look:

<?php

echo 'Hello world!'; // Will print the string "Hello world!"

echo '<p>Hello world!</p>'; // Will print the string "<p>Hello world!</p>"

echo 2; // Will print the string "2" - echo can convert some data types to strings.
echo 2 * 4; // Will print the string "8" - echo can do operations then convert some types.
echo 2 * "4"; // Will print the string "8" but please don't mix data types carelessly like this.
echo array( 'eggs', 'milk' ); // Will print just the word "Array" -
// echo cannot meaningfully convert some data types, such as arrays, to strings.
echo true; // Will print the string "1" - Why? Because 1 is computer for "true."
// In other words, data type conversions can get messy in PHP. Don't be careless just because it lets you.
// In other words: Why are you echoing a boolean?

?>

Does the stuff above feel kind of random and hard to keep track of? It is, in a way. PHP is what’s called a loosely typed programming language: one where data types can fly around without you needing to be disciplined about specifying them.

That frees you to write faster, sort of, but it also opens the door for lots of coding confusion if you become as lazy as the language lets you be.

To be clear, this loose typing isn’t a quirky, random piece of PHP trivia: it’s a big deal in programming land, and the source of a lot of animosity toward PHP itself.

In many programmers’ minds, for a novice coder to be able to type in <?php echo 2 * "4" * true; ?>, refresh their browser and get “8,” and think “Great, that worked!” is basically pure chaotic evil distilled down into a programming language. I’m not sure I disagree with them, either—but here we are.

Finer Points of echo

These are some additional things to understand about PHP’s echo to round out your understanding.

echo is Function-Like, but Not a Function

echo is very similar to a PHP function, like str_replace(): in both cases, you invoke the name to do a predictable bit of work.

However, echo is not technically a function, but rather a “language construct.”

What does this difference mean to you and me? Basically, echo doesn’t use parentheses. There’s no need to write echo( 'Hello' );—in fact, echo 'Hello'; is more correct, although PHP will understand the first bit of code as well. Enough said about this.

echo is Not PHP’s Only Way to Output HTML (of Course)

It may not surprise you that echo isn’t actually the only game in town for outputting HTML content in PHP. That would be too simple, and life and its programming languages are complicated.

Some other ways of outputting HTML content in PHP besides echo (not a complete list) include:

  • print, a language construct extremely similar to echo that I’ve, personally, never seen anybody actually use.
  • var_dump(), a massively useful function that prints out information about PHP data of any data type—strings, numbers, booleans, objects, arrays, and more. It’s not designed for users to see, but rather to help developers debug their code.
  • print_r(), which is like var_dump() but more “readable,” which is apparently what the _r stands for.

We mention these other elements so that the PHP wizards reading this don’t feel the need to post too many “Actually…” corrections in the comments. If you’re just learning PHP, my advice for now is to pretend this whole subsection doesn’t exist.

echo is Closely Tied in With WordPress’s the_() Functions

Now that you understand echo itself, you’re going to really enjoy reading our article on WordPress’s template tags, which describes in detail the difference between WordPress PHP functions like the_title(), which does echo what it retrieves, and get_the_title(), which does not echo what it retrieves.

This function pattern is one of many ways that PHP’s underlying structures are mirrored in WordPress’s PHP codebase and function library.

<?php echo 'Thanks for Reading!'; ?>

You should now understand PHP’s echo. It’s a simple concept in some ways, but it’s also the “faucet” that most PHP code actually emerges from: with some exceptions, the goal of PHP is to output markup, and PHP does that through echo. So to understand echo itself is to understand one of the absolutely most important pieces of a very powerful programming language.

Thank you for taking this step into learning PHP for WordPress development! Please share your thoughts or questions in the comments below, or in our Facebook group.


3 Responses

Comments

  • dimiter kirov says:

    What confuses me in PHP ( my knowledge level is intermediate) is the regex and more precisely when there must be spaces.
    Also my theme developer ( ThemeExpress) largely uses PRINT in the template files.
    Could you write an article about VAR_DUMP() function?
    Thank You for this article too.

  • PHP echo $nice article
    Results == thank you 🙂

  • Mike S. says:

    This paragraph was perfect:

    “We mention these other elements so that the PHP wizards reading this don’t feel the need to post too many “Actually…” corrections in the comments. If you’re just learning PHP, my advice for now is to pretend this whole subsection doesn’t exist.”

    I was just about to ask about these additional commands until you wrote this. Now I 100% get why you added this additional information.

    Say no more! 😀

Add a Comment

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