0
0
PHPprogramming~5 mins

Printf and sprintf formatting in PHP

Choose your learning style9 modes available
Introduction

Printf and sprintf help you create text with numbers or words in a neat, controlled way.

You want to show a number with exactly two decimal places, like a price.
You need to insert variables into a sentence cleanly, like a name or age.
You want to format a date or time in a specific style.
You want to align text or numbers in columns for a report.
You want to build a string with variables but keep the format consistent.
Syntax
PHP
printf(format, arg1, arg2, ...);
sprintf(format, arg1, arg2, ...);

printf prints the formatted string directly.

sprintf returns the formatted string without printing it.

Examples
Prints a greeting with a name inserted.
PHP
printf("Hello %s!", "Alice");
Prints a price with two decimal places.
PHP
$price = 12.5;
printf("Price: $%.2f", $price);
Creates a string with a number padded with zeros to 4 digits.
PHP
$text = sprintf("Number: %04d", 7);
Sample Program

This program shows how to use printf to print formatted text and sprintf to create a formatted string.

PHP
<?php
$name = "Bob";
$age = 30;
$score = 95.6789;

// Print a greeting
printf("Hello %s!\n", $name);

// Print age with label
printf("Age: %d years\n", $age);

// Print score with 2 decimals
printf("Score: %.2f\n", $score);

// Create a formatted string with sprintf
$info = sprintf("Name: %s, Age: %d, Score: %.1f", $name, $age, $score);
echo $info . "\n";
?>
OutputSuccess
Important Notes

Use %s for strings, %d for integers, and %f for floating-point numbers.

You can control decimal places with %.2f (2 decimals) or %.1f (1 decimal).

Remember printf prints immediately, sprintf returns the string for later use.

Summary

Printf and sprintf format text by inserting variables in a controlled way.

Printf prints the result; sprintf returns it as a string.

Use format codes like %s, %d, and %f to specify how variables appear.