18

I've never used these functions before but after reading a lot about sprintf(), I decided I should get to know it.

So I went ahead and did the following.

function currentDateTime() {
  list($micro, $Unixtime) = explode(" ",microtime());
  $sec= $micro + date("s", $Unixtime);
  $sec = mb_ereg_replace(sprintf('%d', $sec), "", ($micro + date("s", $Unixtime)));
  return date("Y-m-d H:i:s", $Unixtime).$sec;
}

sprintf(currentDateTime());

It prints nothing. Using the printf() function on the other hand:

printf(currentDateTime());

It prints the result just fine. So what's the difference between these 2 functions and how do I properly use the sprintf() function?

Annika Backstrom
  • 13,587
  • 6
  • 39
  • 52
KdgDev
  • 13,833
  • 45
  • 117
  • 153

3 Answers3

59

sprintf() returns a string, printf() displays it.

The following two are equal:

printf(currentDateTime());
print sprintf(currentDateTime());
molf
  • 71,048
  • 13
  • 134
  • 117
14

sprintf() prints the result to a string. printf() prints it to standard output ie:

printf(currentDateTime());

is equivalent to:

echo sprintf(currentDateTime());
cletus
  • 599,013
  • 161
  • 897
  • 938
6

sprintf() returns a string while printf() outputs a string. So you'd have to do something like the following:

function currentDateTime() {
  list($micro, $Unixtime) = explode(" ",microtime());
  $sec= $micro + date("s", $Unixtime);
  $sec = mb_ereg_replace(sprintf('%d', $sec), "", ($micro + date("s", $Unixtime)));
  return date("Y-m-d H:i:s", $Unixtime).$sec;
}

$output = sprintf(currentDateTime());
printf($output);

http://www.php.net/sprintf

http://www.php.net/printf

Carl
  • 1,696
  • 1
  • 17
  • 25