Zend PHP 7 Certification – Strings – Formatting

This post covers the Formatting section of the Strings chapter when studying for the Zend PHP 7 Certification.

A number of functions are available in PHP that assist with formatting a string, such as printf and sprintf to name a couple of commonly used ones.

The printf() function outputs a formatted string. There is no fixed amount of parameters that the function created, however the first parameter must be the format.

The format values include:

  • %% – Returns a percent sign
  • %b – Binary number
  • %c – The character according to the ASCII value
  • %d – Signed decimal number (negative, zero or positive)
  • %e – Scientific notation using a lowercase (e.g. 1.2e+2)
  • %E – Scientific notation using a uppercase (e.g. 1.2E+2)
  • %u – Unsigned decimal number (equal to or greather than zero)
  • %f – Floating-point number (local settings aware)
  • %F – Floating-point number (not local settings aware)
  • %g – shorter of %e and %f
  • %G – shorter of %E and %f
  • %o – Octal number
  • %s – String
  • %x – Hexadecimal number (lowercase letters)
  • %X – Hexadecimal number (uppercase letters)

The second argument would be inserted at the first % sign in the format string, the third argument at the second % sign and so on.

$name = 'Bob';
printf("Hello %s", $name); // Outputs: Hello Bob

$numberOfApples = 3;
printf("%s has a total of %d apples", $name, $numberOfApples); // Outputs: Bob has a total of 3 apples

You can also specify a precision character , ., followed by an optional decimal digit string that says how many decimal digits should be displayed for floating-point numbers.

This sits in between the % and the type specifier character. For example, to round a float to the nearest 2 decimal places, write the below.

$costOfApples = 3.998383833883;
printf("The apples cost £%.02f each!", $costOfApples); // Outputs: The apples cost £4.00 each!

The sprintf() function returns a formatted string. Essentially using print sprintf() in PHP is the same as doing printf().

$name = 'Bob';
echo sprintf("Hello %s", $name); // Outputs: Hello Bob

printf and vprintf are almost the same, but vprintf accepts an array of arguments, instead of a variable number of arguments.

vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01

Similar to printf and sprintf, vsprintf returns a formatted string rather than outputting it like vprintf does.

echo vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01

The fprintf() function sends a formatted string to a resource.

if (!($fp = fopen('date.txt', 'w'))) {

fprintf($fp, "%04d-%02d-%02d", $year, $month, $day);

The example above will write the formatted ISO date to a date.txt file.

View the other sections:

Note: This article is based on PHP version 7.1.