Open In App

How to use the printf() Function in PHP ?

The printf( ) function in PHP is a versatile tool used for formatting and displaying text in a specific manner. It allows us to output formatted strings with placeholders for variable values.

This function is particularly useful when you need precise control over the appearance of text, such as aligning columns, specifying decimal precision, or adding leading zeros.

Format Specifiers

Syntax

printf(format_string, arg1, arg2, ...);

Approach

Example:

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

printf("Name: %s, Age: %d", $name, $age);

// Output: Name: John, Age: 30

Difference between printf() and echo

printf() Function echo Statement
Used for formatting and displaying text with placeholders Outputs text directly without formatting
Offers precise control over text appearance using format specifiers Simpler to use for basic text output
Ideal for displaying formatted data or generating complex output Suitable for simple output requirements
Article Tags :