sprintf()
The sprintf() function in PHP formats a string and returns it. It is particularly useful for creating strings with dynamic content. This article covers its syntax, usage, and common format specifiers.
Syntax
string sprintf ( string $format , mixed ...$args )The function requires a mandatory $format string that defines the output structure. The $args parameter is variadic and optional; it accepts zero or more values to replace placeholders in the format string. Note that the variadic syntax (...$args) requires PHP 5.6 or newer.
Here is an example of how to use the sprintf() function:
Example
<?php
$name = 'John';
$age = 25;
$str = sprintf('My name is %s and I am %d years old', $name, $age);
echo $str;
?>In this example, we pass two variables, $name and $age, to replace the %s and %d placeholders in the format string.
The output of this code will be:
My name is John and I am 25 years oldCommon Format Specifiers
The $format string uses placeholders to determine how arguments are displayed:
%s– formats the argument as a string.%d– formats the argument as an integer (strips decimals).%f– formats the argument as a floating-point number.- Padding & Precision – You can control width and decimal places. For example,
%05dpads an integer with leading zeros to a width of 5, and%.2flimits a float to two decimal places.
By mastering sprintf(), you can efficiently generate structured strings with dynamic content, making your PHP code more readable and maintainable.
We hope this guide has helped you understand how to use sprintf() effectively.
Practice
What is true about the sprintf() function in PHP?