Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท String Functions

PHP printf() function

Reference for PHP printf(): print a formatted string, how it differs from sprintf() and echo, the integer it returns and the format errors it throws.

printf() formats its arguments exactly like sprintf() and then writes the result to the output. It returns the length of the printed string in bytes, not a success flag. Use it for quick command-line output and for templates where the text goes straight to the screen; use sprintf() when you need the string itself.

The format language (width, padding, precision, n$ argument numbers and the type specifiers) is identical, so this page only covers what is specific to printing.

PHP
<?php
printf("%s scored %d points\n", "Ada", 95);
// Ada scored 95 points

Try it

PHP Printing and the return value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP A small table and a format error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
printf(string $format, mixed ...$values): int
Name Description
$format The template, with % placeholders. See sprintf() for the full list.
...$values The values to insert.

Return value: the number of bytes written (the length of the formatted string).

Errors: ArgumentCountError when there are too few values; ValueError for an unknown specifier.

Usage notes

  • Return value is a length. Do not test it for success. Bytes, not characters, are counted, so printf("รฉ") returns 2 in UTF-8.
  • No newline is added. Include \n (or PHP_EOL) yourself. In double-quoted strings \n is a newline; in single quotes it is two literal characters.
  • Output is not escaped. In a web page, passing user text to %s is as unsafe as echo. Run it through htmlspecialchars() first.
  • Output buffering applies. Like echo, the text goes through output buffers started by ob_start().
  • When to prefer sprintf(). If you need to log, return, compare or escape the text, build it with sprintf() and print it separately. The result is easier to test.
  • Array of values. Use vprintf() (see vsprintf()) when the arguments are already in an array.
  • fprintf() writes to any stream, for example fprintf(STDERR, "warning: %s\n", $msg).