Format Strings with the sprintf() Function in PHP
Learn how to use the sprintf() function in PHP to format strings. See examples and sample code to help you use this function in your PHP projects. Whether you need to include variables in a string or format numbers and dates, sprintf() is the perfect tool to get the job done.
sprintf()
is a function in PHP that formats a string, much like printf
. The difference between sprintf
and printf
is that sprintf
returns the formatted string, rather than printing it to the screen.
Example:
<?php
$price = 250.5;
$city = "Delhi";
$name = "Ravi Kumar";
$format = "The price of the item is %.2f and it is available in %s, bought by %s";
$result = sprintf($format, $price, $city, $name);
echo $result;
?>
Output:
The price of the item is 250.50 and it is available in Delhi, bought by Ravi Kumar
Another example:
<?php
$date = "2023-01-30";
$time = "11:30 AM";
$event = "Meeting";
$format = "The %s is scheduled for %s at %s";
$result = sprintf($format, $event, $date, $time);
echo $result;
?>
Output:
The Meeting is scheduled for 2023-01-30 at 11:30 AM