PHP 中 printf 的用途是什么?
我什么时候会在 PHP 中使用 printf 而不是 echo?为什么?我只是不明白为什么理解很重要。谢谢!
When would I use printf instead of echo in PHP and why? I just don't understand why it's important to understand. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它的使用方式与 C 中的使用方式相同,将格式化值替换为格式字符串。
sprintf
手册页。您可以实现一些有用的变量格式(零填充、对齐、宽度等),这需要伴随多个函数调用的
echo
。例如,将字符串右对齐并用零填充为 10 个字符,但如果长度超过 10 个字符则截断:
vs
您可以轻松地以八进制、十六进制或二进制格式设置数字,而无需通过函数运行它们,存储结果。放在临时变量中并通过 echo 传递它。
printf
系列函数还有很多很多用途。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:
vs
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 theprintf
family of functions.printf 允许您传递参数,因此您可以执行以下操作:
或者您可以使用 echo 执行相同的操作,但它不那么干净:
它只是您喜欢的一个。
printf allows you to pass parameters so you can do this:
or you can use echo which does the same thing but its not as clean:
It just which one you prefer.
printf()
允许您以某种方式格式化变量。例如,您可以确保放入%d
中的内容始终显示为数字。您可以显示小数点后一定位数的浮点数。您可以用科学记数法显示数字。您可以将数字转换为八进制/十六进制。如果您想使用 echo 执行上述任何操作,则需要先调用某个函数或另一个函数,然后再将这些变量放入双引号字符串中。了解如何使用
printf()
可以让您的工作变得更简单。当您可以使用 sprintf() 获取输出时,它会变得更加强大。
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()
.