PHP String Formatting
In this page:
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
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
$formatted = sprintf("Name: %s, Age: %d", "Alice", 30);
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
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
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
printf("[%10s]\n", "hi");
printf("[%-10s]", "hi");
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: