Monday, 29 September 2014

sprintf in PHP

PHP sprintf() function is utilized to create formatted string from one or more arguments.

Syntax:

sprintf(format,arg1,arg2,arg++)
format : Required. Defines the string and how to format the variables in it.

arg1 : Required. The argument to be added as the first %-sign.

arg2 : Optional. The argument to be added at the second %-sign.

arg++ : Optional. The argument to be added at the third, fourth, etc. %-sign.

Note : The only difference between printf() and sprintf() is that printf() sends the resulting string directly to the output whereas sprintf() returns the result string as its value.

Note : If there are more % signs than arguments, you must use placeholders.

Tip : Related functions: fprintf(), printf(), vfprintf(), vprintf() and vsprintf().

Example:

<?php
$str_name = "Morning!";
$my_name = "Jack.";
$day_num = 100;
$result = sprintf("Good %s My name is %s It is day number %u",$str_name,$my_name,$day_num);
echo $result;
?>
Output will be:
Good Morning! My name is Jack. It is day number 100

0 comments:

Post a Comment