sprintf() function in PHP


The sprintf() function is used to output a formatted string.

Syntax

sprintf(format, arg1, arg2, arg++)

Parameters

  • format − Specifies the string and how to format the variables in it.

  • The following are the possible format values −

    • %% - Returns a percent sign

    • %b - Binary number

    • %c - The character according to the ASCII value

    • %d - Signed decimal number (negative, zero or positive)

    • %e - Scientific notation using a lowercase (e.g. 1.2e+2)

    • %E - Scientific notation using a uppercase (e.g. 1.2E+2)

    • %u - Unsigned decimal number (equal to or greater than zero)

    • %f - Floating-point number (local settings aware)

    • %F - Floating-point number (not local settings aware)

    • %g - shorter of %e and %f

    • %G - shorter of %E and %f

    • %o - Octal number

    • %s - String

    • %x - Hexadecimal number (lowercase letters)

    • %X - Hexadecimal number (uppercase letters)

  • argument1 − The argument to be inserted at the first %-sign in the format string.

  • argument2 − The argument to be inserted at the second %-sign in the format string.

Return

The sprintf() function returns a formatted string.

Example

The following is an example −

 Live Demo

<?php
   $val = 299;
   $txt = sprintf("%f",$val);
   echo $txt;
?>

Output

The following is the output −

299.000000

Example

Let us see another example −

 Live Demo

<?php
   $val = 768776;
   $char = 95;
   echo sprintf("%%b = %b",$val)."<br>";
   echo sprintf("%%c = %c",$char);
?>

Output

The following is the output −

%b = 10111011101100001000
%c = _

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Dec-2019

522 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements