Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - printf and sprintf have different outputs

Tags:

php

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?

like image 903
Sam Avatar asked Dec 09 '25 04:12

Sam


1 Answers

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 
like image 198
Hanky Panky Avatar answered Dec 11 '25 02:12

Hanky Panky