Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is printf used for in PHP?

Tags:

php

printf

When would I use printf instead of echo in PHP and why? I just don't understand why it's important to understand. Thanks!

like image 743
BretHudson Avatar asked Dec 01 '22 04:12

BretHudson


2 Answers

It is used the same way it is used in C, to substitute formatted values into a format string.

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

You can achieve some useful formatting of variables (zero padding, alignment, width etc) which would require an echo accompanied by several function calls.

For example, to right-justify and zero-pad a string to 10 characters, but truncate if longer than 10 characters:

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

vs

 $tmp = '';

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

 echo $tmp;

You can easily format numbers in octal, hexadecimal or binary without the clutter of running them through a function, storing the result in a temporary variable and passing it through echo. There are many, many more uses for the printf family of functions.

like image 98
meagar Avatar answered Dec 06 '22 21:12

meagar


printf allows you to pass parameters so you can do this:

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

or you can use echo which does the same thing but its not as clean:

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

It just which one you prefer.

like image 33
Amir Raminfar Avatar answered Dec 06 '22 20:12

Amir Raminfar