3

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

<?php
    $str_1 = printf("%x%x%x", 65, 127, 245);
    $str_2 = sprintf("%x%x%x", 65, 127, 245);

    echo $str_1 . "\n";
    echo $str_2 . "\n";

the output is this:

417ff56
417ff5

why I have that 6 digit in the first line of output?

1
  • 1
    your $str_1 contains a "6" - length returned by printf Commented Nov 25, 2014 at 7:14

2 Answers 2

9

printf doesnt return the string, it directly outputs it (and returns only its length). Try this

<?php
    printf("%x%x%x", 65, 127, 245);
    $str_2 = sprintf("%x%x%x", 65, 127, 245);
    echo "\n". $str_2 . "\n";
?>

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 
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.