When would I use printf instead of echo in PHP and why? I just don't understand why it's important to understand. Thanks!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With