BretHudson
BretHudson

Reputation: 126

What is printf used for in PHP?

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

Upvotes: 4

Views: 1358

Answers (4)

user229044
user229044

Reputation: 239291

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.

Upvotes: 11

kijin
kijin

Reputation: 8910

printf() allows you to format the variables in a certain way. For example, you can be sure that something that gets put in %d always gets displayed as a number. You can display floating point numbers with a certain number of digits after the decimal point. You can display numbers in scientific notations. You can convert numbers to octal/hex.

If you wanted to do any of the above using echo, you'd need to call some function or another before putting those variables inside a double-quoted string. Knowing how to use printf() makes your job simpler.

And it gets even more powerful when you can grab the output using sprintf().

Upvotes: 2

Vic
Vic

Reputation: 1346

  1. printf — Output a formatted string: https://www.php.net/manual/en/function.printf.php
  2. echo — Output one or more strings: https://www.php.net/manual/en/function.echo.php

Upvotes: 2

Amir Raminfar
Amir Raminfar

Reputation: 34149

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.

Upvotes: 4

Related Questions