Php vsprintf
From w3cyberlearnings
Contents |
PHP function vsprintf
This function writes a formatted string to a variable.
Syntax vsprintf
- format: format string
- arrayArg: array argument to insert at the percent (%) signs.
$variable = vsprintf(format,arrayArg);
format
- % - returns a percent sign.
- b - is an integer and display it as a binary number.
- c - is an integer and display it as a ASCII value.
- d - is an integer and display as a signed decimal number.
- e - is scientific notation with lowercase letter e(e.g. 1.2e+2).
- E - is scientific notation with capital letter E(e.g.1.2E+2).
- u - is an integer, and display as an unsigned decimal number.
- f- is a float, and display as a floating-point number. (local aware)
- F - is a float, and display as a floating-point number (non-locale aware).
- g - is shorter of %e and %f.
- G - is shorter of %E and %f.
- o - is an integer, and display as an octal number.
- s - is string and display as a string.
- x - is an integer and display as a hexadecimal number (with lowercase letters).
- X - is an integer and display as a hexadecimal number (with uppercase letters).
- + - force (+) sign for positive number, and (-) for negative number.
- ' - padding: %'x20s (uses 'x' as padding), %'u20x (uses 'u' as padding)
- - - Left justified variable value
- [0-9] - the minimum width specifies to the width of the variable value.
- .[0-9] - set the decimal digits or maximum of the string width.
Example 1
<?php $jone = vsprintf("%s is %d year old", array("Jone", 38)); echo $jone; ?>
Output
Jone is 38 year old
Example 2
<?php $p1 = array('Bob', '5yrs', 15, 40); $p2 = array('Janny', '5yrs', 12, 40); $p3 = array('Mark', '3yrs', 18, 40); $all_p = array($p1, $p2, $p3); foreach ($all_p as $pp) { $person = vsprintf("%s is having %s experiences, hourly earn: %.2f, work hours:%d<br/>", $pp); echo $person; } ?>
Output
Bob is having 5yrs experiences, hourly earn: 15.00, work hours:40 Janny is having 5yrs experiences, hourly earn: 12.00, work hours:40 Mark is having 3yrs experiences, hourly earn: 18.00, work hours:40
Example 3: Display positive and nagative number
<?php $digit = vsprintf('%+d is greater than %+d', array(3,-120)); echo $digit; ?>
Output
+3 is greater than -120
Example 4: Specifies padding
<?php $joh1 = vsprintf("%'-10s loves<br/>", array("Johne")); echo $joh1; $joh2 = vsprintf("%'+15s loves<br/>", array("Johne")); echo $joh2; $joh3 = vsprintf("%'>15s loves<br/>", array("Johne")); echo $joh3; ?>
Output
-----Johne loves ++++++++++Johne loves >>>>>>>>>>Johne loves
Example 5
<?php $n1 = vsprintf("%04d <br/>", array(134)); echo $n1; $n2 = vsprintf("%05d <br/>", array(134)); echo $n2; $n3 = vsprintf("%06d <br/>", array(134)); echo $n3; ?>
Output
0134 00134 000134