Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • PHP Tutorial
  • PHP Exercises
  • PHP Array
  • PHP String
  • PHP Calendar
  • PHP Filesystem
  • PHP Math
  • PHP Programs
  • PHP Array Programs
  • PHP String Programs
  • PHP Interview Questions
  • PHP GMP
  • PHP IntlChar
  • PHP Image Processing
  • PHP DsSet
  • PHP DsMap
  • PHP Formatter
  • Web Technology
Open In App
Next Article:
PHP String Functions
Next article icon

PHP sprintf() Function

Last Updated : 30 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The sprintf() function is an inbuilt function in PHP that is used for formatting strings in a manner similar to the C language's printf() function. It allows you to create formatted strings by substituting placeholders with corresponding values.

Syntax:

string sprintf(string $format, mixed ...$values)

Parameters: This function accepts two parameters that are described below:

  • $format: This is a string that specifies the format of the output. It contains placeholders that begin with a percent sign (%) followed by a character representing the type of value that should be inserted at that position.
  • $values: These are the values that will replace the placeholders in the format string. You can provide any number of arguments, depending on the number of placeholders in the format string and their types.

Return Values: The sprintf() function returns the string which is produced by this function.

Program 1: The following program demonstrates the sprintf() function.

PHP
<?php  $first_name = "Ram"; $last_name = "Kumar"; $age = 28; $balance = 1200.50;     $formatted_string = sprintf(       "Name: %s %s\nAge: %d\nBalance: $%.2f",        $first_name, $last_name, $age, $balance );     echo $formatted_string;     ?> 

Output
Name: Ram Kumar Age: 28 Balance: $1200.50

Program 2: The following program demonstrates the sprintf() function.

PHP
<?php     $product = "Widget"; $quantity = 10; $pricePerUnit = 24.95;     $totalPrice = $quantity * $pricePerUnit;     $formatted_invoice = sprintf(       "Invoice:\nProduct: %s\nQuantity: %d\nPrice"       . " per Unit: $%.2f\nTotal Price: $%.2f",        $product, $quantity,        $pricePerUnit, $totalPrice );     echo $formatted_invoice;     ?> 

Output
Invoice: Product: Widget Quantity: 10 Price per Unit: $24.95 Total Price: $249.50

Program 3: In this example we iterates through an array of products, formatting and printing them as a table with aligned columns using sprintf() for string formatting.

PHP
<?php    $products = [     ["name" => "Laptop", "price" => 999.99, "quantity" => 2],     ["name" => "Smartphone", "price" => 599.99, "quantity" => 3],     ["name" => "Headphones", "price" => 99.99, "quantity" => 5], ];  // Print table headers echo sprintf("| %-15s | %-10s | %-8s |\n", "Product", "Price", "Quantity"); echo "---------------------------------------\n";  foreach ($products as $product) {   echo sprintf("| %-15s | $%-9.2f | %-8d |\n", $product['name'], $product['price'], $product['quantity']); }   echo "---------------------------------------\n"; ?> 

Output

| Product         | Price      | Quantity |
---------------------------------------
| Laptop | $999.99 | 2 |
| Smartphone | $599.99 | 3 |
| Headphones | $99.99 | 5 |
---------------------------------------

Reference: https://www.php.net/manual/en/function.sprintf.php


Next Article
PHP String Functions
author
neeraj3304
Improve
Article Tags :
  • Web Technologies
  • PHP
  • PHP-string
  • PHP-function

Similar Reads

  • PHP vsprintf() Function
    The vsprintf() function in PHP is an inbuilt function and used to display array values as a formatted string. The array elements will be inserted at the percent (%) signs in the main string. Display array values as a formatted string according to its format and accepts an array argument in place of
    5 min read
  • PHP vprintf() function
    The vprintf() function in PHP is an inbuilt function which is used to display array values as a formatted string Display array values as a formatted string according to format it is work similar as printf() but accepts an array of arguments, in place of variables number of arguments. Returns the len
    5 min read
  • PHP vfprintf() Function
    The vfprintf() function is an inbuilt function in PHP that is used to write formatted information to a stream, such as a file or the output screen. Syntax: vfprintf(resource $stream, string $format, array $values): Parameters: This function accepts three parameters that are described below. $stream:
    2 min read
  • PHP | print_r() Function
    The print_r() function is a built-in function in PHP and is used to print or display information stored in a variable. Syntax: print_r( $variable, $isStore ) Parameters: This function accepts two parameters as shown in above syntax and described below. $variable: This parameter specifies the variabl
    2 min read
  • PHP String Functions
    Strings are a fundamental data type in PHP, used to store and manipulate text. PHP provides a wide variety of built-in string functions. These functions perform various operations such as string transformations, character manipulations, encoding and decoding, and formatting, making string handling s
    6 min read
  • PHP stristr() Function
    The stristr() function is a built-in function in PHP. It searches for the first occurrence of a string inside another string and displays the portion of the latter starting from the first occurrence of the former in the latter (before if specified). This function is case-insensitive. Syntax : strist
    2 min read
  • PHP usort() Function
    PHP comes with a number of built-in functions that are used to sort arrays in an easier way. Here, we are going to discuss a new function usort(). The usort() function in PHP sorts a given array by using a user-defined comparison function. This function is useful in case if we want to sort the array
    2 min read
  • PHP sscanf() Function
    The PHP sscanf() is an inbuilt function in PHP where the input string is parsed according to the specified or a particular pattern, along with comparing & matching any whitespace in between the format string & input string, which means, even the tab(\t) will be comparing & matches a sing
    2 min read
  • PHP sizeof() Function
    In this article, we will see how to get the length of the array using the sizeof() function in PHP. The sizeof() function is a built-in function in PHP and is used to count the number of elements present in an array or any other countable object. Syntax: int sizeof(array, mode);Parameter: This funct
    2 min read
  • PHP strlen() Function
    The strlen() is a built-in function in PHP which returns the length of a given string. It calculates the length of the string including all the whitespaces and special characters. Syntax:strlen($string);Parameters: This parameter represents the string whose length is needed to be returned. Return Va
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences