Skip to content
sprintf and Heredoc
step 1/5

Reading — step 1 of 5

Learn

~1 min readStrings

sprintf returns a formatted string; printf writes it directly:

$s = sprintf("%s is %d years old", "Alice", 30);
echo $s;
printf("%-10s | %5d\n", "score", 95);

Format specifiers: %s (string), %d (decimal int), %f (float), %.2f (2 decimals), %x (hex). Pretty close to C's printf.

Heredoc for multi-line strings (with interpolation):

$name = "Alice";
$msg = <<<END
    Hello, $name!
    Line 2 with $name interpolated.
END;
echo $msg;

Nowdoc (<<<'TAG') is the single-quoted equivalent — literal, no interpolation.

The closing tag must be at column zero of its own line (no leading whitespace) for older PHP. PHP 7.3+ allows indented closers — much friendlier.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…