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">';

Did you know there is a much more readable way to write this though? :O

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.

Jaclyn Tan

I'm Jaclyn and I make websites. I aim to make the web a more fun and accessible place, sharing what I learn along the way.

My blog has no ads or sponsors and I plan on keeping it that way. If you like what I do please consider supporting me.