How to Output Variables within Strings with PHP

Displaying strings isn’t that hard, you just use echo followed by the string in question. But that only gets us so far, what about when we need to use variables inside of the string? Luckily there’s a ton of different ways to accomplish this.

echo

You can easily use echo to output a string with variables, and there’s a few different ways to construct the syntax:

$name = 'Josh'

echo 'Hello ' . $name . '!'
echo 'Hello ', $name, '!'
echo "Hello {$name}!"
echo "Hello ${name}!"
echo "Hello $name!"

All of the aforementioned echo statements will results in “Hello Josh!” being output.

printf

echo is pretty much all I ever use to output strings with or without variables, but maybe that’s not your style. If you’re looking for a slightly more complex way to output strings with variables in them, you could use printf() which allows you to output a string based on a format and by replacing certain specifiers with the variables you pass in. Here’s a simple example using the $name variable we defined above:

printf('Hello %s!', $name

printf supports a wide range of specifiers, the list of them is available here.

Because both approaches result in the same output, [as always] the choice is yours as to which one you decide to use!

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.