Hướng dẫn sprintf vs printf php

I written the following tiny php program to test printf and sprintf:


Output

417ff5
417ff5

Fiddle

Now you might ask why that extra 6 [in your output] then? Becuase printf returns the length of the printed string which is 6 in your case.

So here is how it goes

417ff56            // that extra 6 comes from your first echo.
417ff5 

answered Nov 25, 2014 at 7:13

Hanky PankyHanky Panky

46.2k8 gold badges70 silver badges95 bronze badges

printf :- directly print the formatted string.

sprintf :- convert given format and store values in a variable and you can use echo/print to print variable values.

$text = "65 127 245";
printf["%x%x%x", 65, 127, 245];
$str_2 = sprintf["%x%x%x", 65, 127, 245];
echo $str_2;

answered Nov 25, 2014 at 7:18

Rakesh SharmaRakesh Sharma

13.6k4 gold badges36 silver badges42 bronze badges

Not the answer you're looking for? Browse other questions tagged php or ask your own question.

The Sample  Code below shows the difference between printf vs sprintf

Difference

  • printf will directly print out the String
  • sprintf will save the value as a variable and print it out later

Chủ Đề