PHP's HereDoc versus NowDoc

Josh Sherman
1 min read
Software Development PHP

We’ve previously discussed how to assign variables and add in variables and all of that good stuff, but what about if you are dealing with a large block of text? There’s many approaches, most that require you to be mindful of escaping characters like simply using quotes to wrap a long string or using implode() to join a series of array items into a larger string (I commonly do something similar in Javascript since it’s one of the few viable options). PHP provides 2 additional ways to assign / output variables with Here Document and Now Document syntax (more commonly HereDoc and NowDoc).

$copyright = 'Copyright 2013';

echo <<<'HERE'
	<h1>Testing out HereDoc Syntax</h1>
	<p>Lorem ipsum...</p>
	<footer>$copyright</footer>
HERE;

/**
 * Output:
 *	 <h1>Testing out HereDoc Syntax</h1>
 *	 <p>Lorem ipsum...</p>
 *	 <footer>$copyright</footer>
 */

echo <<<NOW
	<h1>Testing out NowDoc Syntax</h1>
	<p>Lorem ipsum...</p>
	<footer>$copyright</footer>
HERE;

/**
 * Output:
 *	 <h1>Testing out NowDoc Syntax</h1>
 *	 <p>Lorem ipsum...</p>
 *	 <footer>Copyright 2013</footer>
 */

These two approaches are similar, but as you can see, NowDoc not only uses a quotes string (more typing, albeit not a lot) but it also treats the variables as string literals. In my opinion, HereDoc is the only way to fly since it gives you the best of both worlds, shorter syntax (hey, those 2 extra characters add up!) and the ability to inject variables inside of your string.

Also, Happy Veterans Day to all of the men and women that have served or are actively serving in the Armed Forces!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

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.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles