How to Output Strings in PHP

Outputting strings is one of the most common actions when building a web site, and PHP offers a multitude of ways to do so each with their own set of strengths and weaknesses

print

print is a language construct and not a function, so you don’t need any parenthesis to use it. Just call it followed by a string (literal or in a variable) and you’re good to go:

print 'Hello World!'

$hello = 'Hello World!'
print $hello

echo

Like print, echo is a construct and is used exactly the same way but unlike print has a shorthand equivalent as well:

<?='Hello World!'?>
<?=$hello?>

Please keep in mind that you must have PHP configured to allow the shorthand delimiters, which is disabled by default on OS X. Personally, I try to avoid shorthand at all costs because of the mixed behavior across platforms by default.

printf

For those times that you need to format a string in a specific way, you can use printf. The syntax is pretty basic, the first argument is the string with any number of type specifiers that will be swapped out for the rest of the arguments that are passed in. Here’s a “Hello World” example that injects a name into the string:

$name = 'Josh'
printf('Hello %s!', $name

A full list of type specifiers can be found here. Also, this could be easily accomplished with print or echo as well:

echo 'Hello ' . $name . '!'

or even:

echo "Hello {$name}!"

As always the choice is yours as to how you want to output strings. Finding a way that works for you and then sticking to it and being consistent is very valuable when it comes time to refactor. Be sure to subscribe for updates so you don’t miss out on when I discuss heredoc and nowdoc!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.