Skip to content
← Back to Snippets
Code

Heredoc Syntax for Multi-line Strings

Demonstrates heredoc syntax for readable multi-line strings with variable interpolation and returns a trimmed message body.

Purpose

Demonstrates heredoc syntax for readable multi-line strings with variable interpolation and returns a trimmed message body.

Snippet details

ContextStringLevelPracticalCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Heredoc Syntax for Multi-line Strings.
 *
 * Purpose:
 * Builds a readable multi-line string while allowing PHP variables to be
 * interpolated inside the text.
 *
 * @param string $captain_name Captain or sender name.
 * @param string $ship_name Ship name to include in the message.
 * @return string Multi-line message body.
 */
function ogSnippetHeredocSyntax(string $captain_name, string $ship_name): string {
	$captain_name = trim($captain_name);
	$ship_name = trim($ship_name);

	if ($captain_name === '') {
		$captain_name = 'Unknown Captain';
	}

	if ($ship_name === '') {
		$ship_name = 'Unknown Ship';
	}

	$message = <<<MISSION
Captain: $captain_name
Ship: $ship_name
Status: Engines online and route plotted.
MISSION;

	return trim($message);
}

$heredoc_message = ogSnippetHeredocSyntax('James T. Kirk', 'Enterprise');

echo $heredoc_message;