PHP printf() Function - Complete Guide

What is the PHP printf() Function?

The printf() function in PHP allows you to format strings dynamically by replacing placeholders with variable values. It is especially useful for controlling how data (numbers, text, or special formats) appears in the output.

Syntax

int printf(string $format, mixed ...$values);

Parameters:

  1. $format: A string containing placeholders (format specifiers) for formatting output.
  2. $values: Variable values to replace placeholders in the format string.

Return Value:

  • Returns the length of the outputted string.

Common Format Specifiers

PlaceholderDescriptionExample Output
%dDecimal integer42
%fFloating-point number3.14
%sStringHello
%xHexadecimal (lowercase)2a
%XHexadecimal (uppercase)2A
%bBinary representation101010
%eScientific notation1.23e+4

Basic Example

<?php
$name = "Alice";
$age = 30;
printf("My name is %s, and I am %d years old.", $name, $age);
?>

Output:

My name is Alice, and I am 30 years old.

Formatting Numbers

1. Floating-Point Numbers

<?php
$pi = 3.14159265359;
printf("The value of pi is %.2f", $pi);
?>

Output:

The value of pi is 3.14

2. Padding Numbers

<?php
$number = 7;
printf("Padded number: %04d", $number);
?>

Output:

Padded number: 0007

Alignment and Width Control

<?php
printf("%-10s %-10s\n", "Name", "Age");
printf("%-10s %-10d\n", "John", 25);
printf("%-10s %-10d\n", "Alice", 30);
?>

Output:

Name       Age      
John       25       
Alice      30       
 

Hexadecimal and Binary Representations

<?php
$number = 42;
printf("Hexadecimal: %x, Binary: %b", $number, $number);
?>

Output:

Hexadecimal: 2a, Binary: 101010

Best Practices

  • Match Placeholders to Data Types: Use the appropriate specifier (%d, %f, %s) for the data type.

  • Escape Literal Percent Signs: Use %% to include a literal % in the output.

printf("Completion: 50%%");
  • Specify Precision for Floating Numbers: Avoid long decimal outputs by using precision specifiers like %.2f.

  • Align Output in Tables: Use width specifiers (e.g., %10s) to create neatly aligned tabular data.

Common Mistakes

  • Type Mismatch: Ensure the type of variables matches the specifier. Using %d with a string may cause unexpected results.

  • Placeholder Count: The number of placeholders in $format must match the number of $values.

  • Ignoring Locale: If localization is needed, ensure your format adheres to locale-specific conventions (e.g., , vs . in numbers).

Use Cases

Generating Reports

<?php
$name = "Bob";
$score = 85.5;
printf("Student: %s, Score: %.1f%%", $name, $score);
?>

Output:

Student: Bob, Score: 85.5%

Difference Between printf() and sprintf()

Featureprintf() (Output)sprintf() (Return String)
Output LocationDirectly outputs the stringReturns formatted string for further use