Interpolating variables and multiline markup in PHP

Last modified March 29, 2021
.* :☆゚

When you’re writing PHP, you may be familiar with string operators, like below:

return '<img src="' . $img_src . '" alt="' . $alt . '" class="icon" loading="lazy">';

Personally, I find this method very cumbersome to write, and annoying to read, but it can be easy to fall back to this method because it is similar to JavaScript’s string concatenation.

Unlike JavaScript though, interspersing markup and PHP variables favours the use of double quotes over single quotes, and with double quotes we can write much cleaner, readable code.

If I am writing single lines of markup, using double quotes can save you from having to rely on string operators:

return "<img src='$img_src' alt='$alt' class='icon' loading='lazy'>";

Notice how the quotation marks are now switched around to the previous example. Double quotes are essential for this method, but the advantage here is that you do not need to write periods before and after every variable, which makes your code a lot more readable.

You can also use complex curly syntax if you want to access any array/object values directly in your markup. For example:

return "<img src={$img_src[0]}' alt='{$alt}' class='icon' loading='lazy'>";

If you need to write multiline markup however, you may want to use heredoc syntax:

function my_wp_nav_menu_objects( $items, $args ) {
	foreach( $items as &$item ) {
		$icon = get_field('icon', $item);
		$size = 'large';
		$img_src = wp_get_attachment_image_url( $icon, $size );
		$img_srcset = wp_get_attachment_image_srcset( $icon, $size );
		$title = get_post($icon)->post_title;
		$alt = isset(get_post_meta($icon, '_wp_attachment_image_alt')[0]) ? get_post_meta($icon, '_wp_attachment_image_alt')[0] : $title;

		// append icon
		if( $icon ) {
			$item->title = <<<EOT
			<img src="$img_src"
			<div class="title">$item->title</div>

	return $items;
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);

Heredoc syntax is extremely useful because it retains indentation, and you can also intersperse PHP variables within the markup as needed. I personally find this syntax very useful for appending markup to menus in WordPress.