In this tutorial, you shall learn how to format a string in PHP using sprintf() function, with the help of example programs.
PHP – Format String
To format a string in PHP, you can use the sprintf() function. Call the sprintf() function, and pass the format string and the values as arguments.
</>
Copy
sprintf(format, value1, value2, .., valueN)
The number of values we pass as arguments depend on the number of specifiers we use in the format.
The function returns the formatted string. You can store it in a variable and use it further in the program.
Example
Consider the following program, where we format a string.
PHP Program
</>
Copy
<?php>
$name = "apple";
$quantity = 30;
$format = "We have $name in our stock, a quantity of $quantity.";
$resulting_string = sprintf($format, $name, $quantity);
echo $resulting_string;
?>
Output
Reference to related tutorials for program
Related Tutorials
- PHP – Difference between printf() and sprintf() function.
Conclusion
In this PHP Tutorial, we learned how to format is string, using sprintf() function.