PHP sprintf() Function

sprintf() is a function in PHP that allows you to format strings using placeholders. It works similarly to printf() but instead of printing the formatted string, it returns it. This can be very useful when you want to store the formatted string in a variable or use it in further processing.

Here's a simple example to demonstrate how sprintf() works:

In this example:

  • %d is a placeholder for an integer.
  • %s is a placeholder for a string.
  • %.2f is a placeholder for a floating-point number (with two decimal places).

 
$number = 42;
$string = "Hello, world!";
$pi = 3.14159265359;
// Using sprintf to format variables into a string
$formatted_string = sprintf("The number is %d. The string is '%s'. Pi is approximately %.2f.", $number, $string, $pi);
echo $formatted_string;
 

Here's a breakdown of the sprintf() line:

  • sprintf() takes a format string as its first argument, followed by a list of variables that will be substituted into the format string.
  • In the format string, placeholders are used to specify where and how the variables should be inserted.
  • The placeholders start with a % symbol, followed by a character that indicates the type of variable (d for integers, s for strings, and f for floating-point numbers). The . followed by a number (%.2f) specifies the precision for floating-point numbers (in this case, two decimal places).
  • The variables to be inserted are listed after the format string in the same order as the placeholders.