Open In App

How to use the printf() Function in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • %s: String
  • %d or %i: Integer
  • %f: Floating-point number
  • %c: Character
  • %b: Binary
  • %o: Octal
  • %x or %X: Hexadecimal
  • %e or %E: Scientific notation

Syntax

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

Approach

  • Using Format Specifiers: Define placeholders in the format string using percent (%) signs followed by format specifiers.
  • Passing Arguments: Provide values for placeholders as additional arguments to the printf() function.
  • Formatting Options: Use format specifiers to specify various formatting options such as decimal precision, padding, alignment, and more.

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads