I\'m looking at Webmonkey\'s PHP and MySql Tutorial, Lesson 2. I think it\'s a php literal. What does %s
mean? It\'s inside the print_f()
function i
The printf()
or sprintf()
function writes a formatted string to a variable.
Here is the Syntax:
sprintf(format,arg1,arg2,arg++)
format:
arg1:
arg2:
arg++:
Example 1:
$number = 9;
$str = "New York";
$txt = sprintf("There are approximately %u million people in %s.",$number,$str);
echo $txt;
This will output:
There are approximately
9
million people inNew York
.
The arg1, arg2, arg++ parameters will be inserted at percent (%) signs in the main string. This function works "step-by-step". At the first % sign, arg1 is inserted, at the second % sign, arg2 is inserted, etc.
Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and "\$". Let see another Example:
Example 2
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f
With no decimals: %1\$u",$number);
echo $txt;
This will output:
With 2 decimals:
123.00
With no decimals:123
Another important tip to remember is that:
With
printf()
andsprintf()
functions, escape character is not backslash '\' but rather '%'. Ie. to print '%' character you need to escape it with itself:
printf('%%%s%%', 'Nigeria Naira');
This will output:
%Nigeria Naira%
Feel free to explore the official PHP Documentation