0

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?

5 Answers 5

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

Comments

3

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

Comments

1

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

2 Comments

I am asking the reason of above output dear?
3 is the length of that was returned from printf
1
$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

2 Comments

But Why 5.3 first then ABC and then 3? I know the mechanisim but according to code it should be ABC5.33?
Because printf() generates output (in your case, the value '5.3') as well as setting a variable value... it effectively does an echo itself... "Output a formatted string".... you're executing the printf() as your first line, so it's the first output sent to php://output
1

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

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.