Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does %S mean in PHP, HTML or XML?

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 in the while loops in at least the first couple of code blocks.

printf("<tr><td>%s %s</td><td>%s</td></tr>n", ...

like image 432
Wolfpack'08 Avatar asked Jul 24 '12 02:07

Wolfpack'08


People also ask

What is %s and %D in PHP?

From the documentation: d - the argument is treated as an integer, and presented as a (signed) decimal number. s - the argument is treated as and presented as a string.

What is the use of Sprintf in PHP?

The sprintf() function writes a formatted string to a variable. The arg1, arg2, ++ 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.


1 Answers

with printf or sprintf characters preceded by the % sign are placeholders (or tokens). They will be replaced by a variable passed as an argument.

Example:

$str1 = 'best'; $str2 = 'world';  $say = sprintf('Tivie is the %s in the %s!', $str1, $str2); echo $say; 

This will output:

Tivie is the best in the world!

Note: There are more placeholders (%s for string, %d for dec number, etc...)


Order:

The order in which you pass the arguments counts. If you switch $str1 with $str2 as

$say = sprintf('Tivie is the %s in the %s!', $str2, $str1);  

it will print

"Tivie is the world in the best!"

You can, however, change the reading order of arguments like this:

$say = sprintf('Tivie is the %2$s in the %1$s!', $str2, $str1); 

which will print the sentence correctly.


Also, keep in mind that PHP is a dynamic language and does not require (or support) explicit type definition. That means it juggles variable types as needed. In sprint it means that if you pass a "string" as argument for a number placeholder (%d), that string will be converted to a number (int, float...) which can have strange results. Here's an example:

$onevar = 2; $anothervar = 'pocket'; $say = sprintf('I have %d chocolate(s) in my %d.', $onevar, $anothervar); echo $say; 

this will print

I have 2 chocolate(s) in my 0.

More reading at PHPdocs

like image 67
Tivie Avatar answered Sep 22 '22 22:09

Tivie