sprintf() : Formatting strings for numbers, and other data types

The PHP sprintf() function is used to format a string according to a specified format. It returns a formatted string, allowing you to customize how variables are displayed, such as formatting numbers, padding strings, and more.

Syntax

string sprintf ( string $format [, mixed $values ] )
$format: A string specifying how to format the values.
$values: The variables to format.
Return Value: A formatted string based on the input.

Basic Example of sprintf()

Here’s a simple example where we format a string with a name and a score:
$name = "John";
$score = 90;
echo sprintf("Student %s scored %d points", $name, $score);
Output:
Student John scored 90 points

Formatting Decimal Numbers

This example demonstrates how to format a floating-point number to two decimal places:
$price = 123.456;
echo sprintf("The price is %.2f", $price);
Output:
The price is 123.46

Padding Numbers with Leading Zeros

You can pad numbers with leading zeros using sprintf():
$order = 42;
echo sprintf("Order number: %05d", $order);
Output:
Order number: 00042

Truncating Strings

Use sprintf() to limit the output of a string to a specified number of characters:
$text = "This is a long string";
echo sprintf("%.10s", $text); // Truncate to 10 characters
Output:
This is a 

Formatting with Multiple Data Types

sprintf() can handle multiple data types in a single formatted string:
$age = 25;
$height = 5.8;
echo sprintf("Age: %d, Height: %.1f feet", $age, $height);
Output:
Age: 25, Height: 5.8 feet

Converting to Hexadecimal and Octal

sprintf() can also be used to convert numbers to other bases, such as hexadecimal and octal:
$number = 255;
echo sprintf("Hex: %X, Octal: %o", $number, $number);
Output:
Hex: FF, Octal: 377

PHP sprintf() Format Specifiers

Specifier Description
%s String
%d Integer (signed decimal number)
%f Floating-point number
%.2f Floating-point number with 2 decimal places
%05d Padded integer with leading zeros (5 digits)
%x Hexadecimal number (lowercase)
%X Hexadecimal number (uppercase)
%o Octal number
%c Character corresponding to an ASCII value
%% A literal percent sign

Conclusion

The sprintf() function in PHP is a versatile tool for formatting strings. It allows you to handle different data types, format numbers, and control the output with precision, making it a powerful function for displaying dynamic content.
String Functions Remove HTML tags
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com











    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer