传递给printf()
的附加参数的顺序必须与格式字符串中的转换规范的顺序相匹配。
在PHP中,可以更改转换规范的顺序,但无法更改参数的顺序。
可以交换进来的参数。在每个百分比(%
)符号后,添加要引用的参数的位置。1
是格式字符串后的第一个参数,2
是第二个参数,依此类推,数字之后跟一个美元($
)符号。
示例代码
<?php
$mailbox = "Inbox";
$totalMessages = 36;
$unreadMessages = 4;
printf("You have %d messages in your %s, of which %d are unread", $totalMessages, $mailbox, $unreadMessages);
printf("Your %2$s contains %3$d unread messages, and %1$d messages in total.", $totalMessages, $mailbox, $unreadMessages);
?>
执行上面示例代码,得到以下代码:
You have 36 messages in your Inbox, of which 4 are unread
Notice: Undefined variable: s in D:\\test.php on line 7
Notice: Undefined variable: d in D:\\test.php on line 7
Notice: Undefined variable: d in D:\\test.php on line 7
Your contains unread messages, and messages in total.
printf()
的变体是fprintf()
,它可将结果字符串写入打开的文件中。