echo() 函数

定义和用法

echo() 函数输出一个或多个字符串。

语法

echo(strings)
参数描述
strings 必需。一个或多个要发送到输出的字符串。

 

 

提示和注释

注释:echo() 实际上不是一个函数,因此您无需对其使用括号。不过,如果您希望向 echo() 传递一个或多个参数,那么使用括号会发生解析错误。

提示:echo() 函数比 print() 函数快一点点。

提示:echo() 函数可以使用简化语法。参见例子 5。

例子 1

<?php
$str = "Who's John Adams?";
echo $str;
echo "<br />";
echo $str."<br />I don't know!";
?>

输出:

Who's John Adam?
Who's John Adam?
I don't know!

例子 2

<?php
echo "This text
spans multiple
lines.";
?>

输出:

This text spans multiple lines.

例子 3

<?php
echo 'This ','string ','was ','made ','with multiple parameters';
?>

输出:

This string was made with multiple parameters

例子 4

单引号和双引号的不同之处。单引号仅输出变量名,而不是值:

<?php
$color = "red";
echo "Roses are $color";
echo "<br />";
echo 'Roses are $color';
?>

输出:

Roses are red
Roses are $color

例子 5

简化语法:

<html>
<body>

<?php
$color = "red";
?>

<p>Roses are <?=$color?></p>

</body>
</html>

print() 函数

定义和用法

print() 函数输出一个或多个字符串。

print(strings)
参数描述
strings 必需。发送到输出的一个或多个字符串。

 

 

提示和注释

注释:print() 函数实际上不是函数,所以您不必对它使用括号。

注释:print() 函数稍慢于 echo()

例子 1

<?php
$str = "Who's John Adams?";
print $str;
print "<br />";
print $str."<br />I don't know!";
?>

输出:

Who's John Adams?
Who's John Adams?
I don't know!

例子 2

<?php
print "This text
spans multiple
lines.";
?>

输出:

This text spans multiple lines.

例子 3

<?php
$color = "red";
print "Roses are $color";
print "<br />";
print 'Roses are $color';
?>

输出:

Roses are red
Roses are $color

sprintf() 函数

定义和用法

sprintf() 函数把格式化的字符串写入一个变量中

语法

sprintf(format,arg1,arg2,arg++)
参数描述
format 必需。转换格式。
arg1 必需。规定插到 format 字符串中第一个 % 符号处的参数。
arg2 可选。规定插到 format 字符串中第二个 % 符号处的参数。
arg++ 可选。规定插到 format 字符串中第三、四等等 % 符号处的参数。

 

 

 

 

说明

参数 format 是转换的格式,以百分比符号 ("%") 开始到转换字符结束。下面的可能的 format 值:

  • %% - 返回百分比符号
  • %b - 二进制数
  • %c - 依照 ASCII 值的字符
  • %d - 带符号十进制数
  • %e - 可续计数法(比如 1.5e+3)
  • %u - 无符号十进制数
  • %f - 浮点数(local settings aware)
  • %F - 浮点数(not local settings aware)
  • %o - 八进制数
  • %s - 字符串
  • %x - 十六进制数(小写字母)
  • %X - 十六进制数(大写字母)

arg1arg2++ 等参数将插入到主字符串中的百分号 (%) 符号处。该函数是逐步执行的。在第一个 % 符号中,插入 arg1,在第二个 % 符号处,插入 arg2,依此类推。

提示和注释

注释:如果 % 符号多于 arg 参数,则您必须使用占位符(指变量位置)。占位符插到 % 符号后面,由数字和 "\$" 组成。请参见例子 3。

例子 1

<?php
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>

输出:

Hello world. Day number 123

例子 2

<?php
$number = 123;
$txt = sprintf("%f",$number);
echo $txt;
?>

输出:

123.000000

例子 3

<?php
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f<br />With no decimals: %1\$u",$number);
echo $txt;
?>

输出:

With 2 decimals: 123.00 
With no decimals: 123