Forum Moderators: coopster

Message Too Old, No Replies

need help understanding tag

%s

         

Sarah Atkinson

2:55 pm on Jun 9, 2005 (gmt 0)

10+ Year Member



I'm just not following this line and there are dozens of lines just like it in this code.

Sql_Query(sprintf('update %s set title = "%s",owner = %d where id = %d', $tables["subscribepage"],$title,$owner,$id));}

What is with the %? Varriables have to start with $ so what are they?

Timotheos

3:37 pm on Jun 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Sarah,

They're the way the sprintf [php.net] function formats the variables that follow. Check out the manual and you can see what it's doin'.

Tim

Holzberg

8:03 pm on Jun 9, 2005 (gmt 0)

10+ Year Member



Look at it this way:

'%s %s %d %d'
$tables["subscribepage"],$title,$owner,$id

OR

sprintf('%s %s %d %d',$tables["subscribepage"],$title,$owner,$id);

notice the first %s will get replaced with $tables["subscribepage"], the second %s will get replaced with $title, the first %d will get replaced with $owner, and the second %d will get replaced with $id.

%s means you are putting a string there and %d means you are putting a decimal there.

for every %<letter> there must be a variable and they all must be in the correct order.

Does that help?

Sarah Atkinson

8:09 pm on Jun 9, 2005 (gmt 0)

10+ Year Member



So why do they do it?
Is this just good coding practice?
Or is it for a specific reason?

mcibor

9:13 pm on Jun 9, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It's a echoing method taken direct from c and c++. It may be helpful if you wish to convert variables to specified format: %d is int, %e is scientific notation and %f is float (%s is string).

Therefore notice difference:

sprintf("This is int: %d, this is float: %f", 12.345, 12.345);

To do this with echo or normal print you would have to write:

$a = 12.345;
echo "This is int: ".(int)$a.", this is float: ".$a;

Both methods are giving the same result. I cannot say which is better and which you should use.
Hope this cleares things a bit
Michal Cibor

More about this function you will find here: [php.net...]