PHP String Formatting
In this page:
printf("format with %s and %d", $string, $number);
$text = sprintf("%.2f", $float); // returns the string instead of printing
Basic printf Output
printf() builds a formatted string using placeholders — %s for a string, %d for an integer — and prints the result immediately once every placeholder has been filled in with the corresponding argument's value.
Example: Basic printf Output
<?php
// Call `printf("Name: %s, Age: %d", "Alice", 30)`
printf("Name: %s, Age: %d", "Alice", 30);
?>
Login to try C/C++/Java/PHP code in the editor
Returning Formatted Strings
sprintf() uses the exact same placeholder syntax as printf(), but instead of printing the result right away, it returns the formatted string as a value — letting you store it, pass it to another function, or build it up before deciding whether to output it at all.
Example: Returning Formatted Strings
<?php
// Declare `$formatted`, set to `sprintf("Name: %s, Age: %d", "Alice", 30)`
$formatted = sprintf("Name: %s, Age: %d", "Alice", 30);
// Print `$formatted` to the output
echo $formatted;
?>
Login to try C/C++/Java/PHP code in the editor
Formatting Decimals
A format specifier like %.2f controls exactly how many digits appear after the decimal point when formatting a float — %.2f on 3.14159 produces '3.14', rounding to two decimal places rather than truncating or printing the full precision.
Example: Formatting Decimals
<?php
// Call `printf("%.2f", 3.14159)`
printf("%.2f", 3.14159);
?>
Login to try C/C++/Java/PHP code in the editor
Using number_format
number_format() is purpose-built for displaying money and other large numbers: it inserts thousands separators automatically and lets you specify a fixed decimal precision, turning 1234567.891 into a reader-friendly '1,234,567.89' in one call.
Example: Using number_format
<?php
// Print `number_format(1234567.891, 2)` to the output
echo number_format(1234567.891, 2);
?>
Login to try C/C++/Java/PHP code in the editor
Padding Strings with sprintf
sprintf()'s width specifiers (like %10s) pad a value out to a fixed total width, right- or left-aligning it as needed.
That fixed-width alignment is exactly what you need when printing tabular data that has to line up visually in evenly spaced columns.
Example: Padding Strings with sprintf
<?php
// Call `printf("[%10s]\n", "hi")`
printf("[%10s]\n", "hi");
// Call `printf("[%-10s]", "hi")`
printf("[%-10s]", "hi");
?>
Login to try C/C++/Java/PHP code in the editor
- Using the wrong placeholder, such as
%dfor a decimal number, which truncates it to an integer. - Passing fewer arguments than placeholders to
printf, which throws anArgumentCountError. - Using
number_format()and then doing math on the result, when it returns a string with commas, not a number.
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: