Awais Qarni
Awais Qarni

Reputation: 18006

Curious about Output of printf

Hello today I was reading about printf in PHP. printf outpust a formatted string. I have a string. I was about to format the floating point string like

 $str = printf('%.1f',5.3);

I know about format %.1f means. Here 1 is number of decimal places. If I echo $str like

echo $str; 

It outputs

5.33

I can understand the output because 5.3 is the string and 3 is the lenght of outputed string which is the return value of printf.

But see my following code

$str = printf('%.1f', '5.34');
echo 'ABC';
echo $str;

It outputs

5.3ABC3

I wonder how it is happening? If we go simple PHP interpolation it should output ABC first then it should output 5.33 because we are formatting only 5.33 not ABC.

Can any one guide me what is happening here?

Upvotes: 0

Views: 238

Answers (5)

Sarwar Hasan
Sarwar Hasan

Reputation: 1641

printf is like a echo command.It display output by itself and it returns length of string which it is displayed.

if you want to get the output into a variable then you need to add

$str=sprintf('%.1f',5.3);
echo 'ABC';
echo $str; 
// now the output will be "ABC5.3

Thanks

Upvotes: 3

ABorty
ABorty

Reputation: 2522

Place echo "<br>" after every line.You will understand how it is happening.

$str = printf('%.1f', '5.34');    output is 5.3
echo "<br>";
echo 'ABC';    output is ABC
echo "<br>";
echo $str;    output is 3

Upvotes: 5

Andreas
Andreas

Reputation: 5599

You gave the answer yourself: printf outputs a formatted string and returns the length of the string.

So:

$str = printf('%.1f', '5.34'); // prints 5.3
echo 'ABC';                    // prints ABC
echo $str;                     // prints 3

Which altogether is: 5.3ABC3

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

$str = printf('%.1f', '5.34'); // outputs '5.3' and sets $str to 3 (the length)
echo 'ABC';                    // outputs 'ABC'
echo $str;                     // outputs the value of $str (i.e. '3')

hence

'5.3', then 'ABC' then '3'

giving

5.3ABC3

Upvotes: 1

Baba
Baba

Reputation: 95111

printf would Output a formatted string and returns the length of the outputted string not the formatted string. You should be using sprintf instead

$str = sprintf('%.1f',5.3);

The reason for 5.3ABC3

 5.3  ----------------  printf('%.1f', '5.34'); and $str  becomes 3 
 ABC  ----------------  echo 'ABC';
 3    ----------------  length of 5.3 which is $str

Upvotes: 1

Related Questions