What is the function sprintf() used for in PHP?

The sprintf() function in PHP is used to format a string with placeholders that are replaced by the values of variables. This function is particularly useful when you need to construct a string that includes variables or values that need to be formatted in a specific way, such as adding leading zeros, specifying the number of decimal places, or aligning text.

$name = "John";
$age = 30;

// Using sprintf() to format a string with placeholders
$formattedString = sprintf("Hello, my name is %s and I am %d years old.", $name, $age);

echo $formattedString;