What is printf used for PHP?

When will I use printf instead of echo in PHP and why? I just don’t understand why this is important to understand. Thank!

+3
source share
4 answers

It is used in the same way as it is used in C to replace formatted values ​​with a format string.

There are literally hundreds of examples of its use on the page sprintf.

You can get useful formatting of variables (zero padding, alignment, width, etc.), for which it will be required echo, accompanied by several function calls.

For example, for right-justification and null input of a line up to 10 characters, but truncate if longer than 10 characters:

 printf('[%010.10s]', $string);

against

 $tmp = '';

 if (strlen($string) > 10)
   $tmp = substr($string, 0, 10);
 else
   $tmp = str_pad($x, 10, '0', STR_PAD_LEFT);

 echo $tmp;

, , echo. printf .

+10

printf , :

printf("My name is %s and my favorite color is %s", $name, $color);

, , :

echo "My name is $name and my favorite color is $color"

, .

+4

printf() . , , -, %d, . . . /.

- , , - , . , printf(), .

, sprintf().

+2

Source: https://habr.com/ru/post/1774437/


All Articles