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:
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.
<?php
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.
<?php
echo vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); // 1988-08-01
The fprintf()
function sends a formatted string to a resource.
<?php
if (!($fp = fopen('date.txt', 'w'))) {
return;
}
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.