sprintf() function in php
0 2215
PHP sprint() function is used to write a formatted string to a variable. It is an inbuilt function of PHP.
Note: Also read fprint() and print() function for same reference.
Syntax:
sprintf($format,$arg1,$arg2,$arg++);
1. $format represents the string and rules to format the variables inside the string. It is mandatory. It has 15 possible values.
- %%: It returns a percent sign.
- %b: It used for binary numbers.
- %c: it used to format characters according to ASCII values.
- %e: It used for the scientific notation in lowercase.
- %E: Scientific notation in uppercase.
- %u: Negative unsigned decimal numbers.
- %f: Floating point numbers (local setting aware).
- %F: Floating point numbers (Not local setting aware).
- %g: Shorter of %e and %f.
- %G: Shorter of %E and %f.
- %o: Octal numbers.
- %s: String.
- %x: Lowercased hexadecimal numbers.
- %X: Uppercased hexadecimal numbers.
- %d: Signed decimal numbers (Negative, Zero, or Positive).
2. $arg1 represents an argument which inserted at the first formatted string. It is mandatory.
3. $arg2 represents an argument which inserted at the second formatted string. It is optional.
4. $arg++ is also optional and its inserted at the next formatted string.
Example:
<?php $str="Shyam"; $f_number=9; $price=500; $result=sprintf("Ram and his friend %s bought %d apples in rupees %f",$str,$f_number,$price); echo $result; ?>
Output:
Share:
Comments
Waiting for your comments