dongyi5570
2017-11-07 14:33
浏览 49
已采纳

为什么这个printf输出重复27?

<?php

$letters = range(A,Z);

$format_string = '<li><a href="#%s">%s</a></li>';

foreach ($letters as $key => $letter) {
    echo printf($format_string,$letter, $letter);
}

?>

This is meant to print out an li with the alphabet from A-W, however the output looks like this:

  • A

    27

  • B

    27

etc.. all the way up to the last number.

Using a regular echo with string concatenation outputs the list fine without any 27's.

图片转代码服务由CSDN问答提供 功能建议

 &lt;?php 
 
 $ letters = range(A,Z); 
 \  n $ format_string ='&lt; li&gt;&lt; a href =“#%s”&gt;%s&lt; / a&gt;&lt; / li&gt;'; 
 
foreach($ letters as $ key =&gt; $ letter)  {
 echo printf($ format_string,$ letter,$ letter); 
} 
 
?&gt; 
   
 
 

这是打印出来的 带有AW字母的li,但输出如下:

  • A

    27

  • B

    27

    等..所有 直到最后一个数字的方式。

    使用带字符串连接的常规回显输出列表没有任何27个。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanmanmian7589 2017-11-07 14:37
    已采纳

    You're calling echo with the return value of the call to printf, which is defined in the manual as

    Returns the length of the outputted string.

    So your printf call is running, and displaying your string. This is returning 27, which is the length of the string <li><a href="#%s">%s</a></li> once a single letter has been inserted into it. The call to echo is then displaying that after the string itself has been shown.

    In short, either remove echo or as mentioned in a comment, use sprintf instead, which returns the string instead of displaying it.

    点赞 打赏 评论

相关推荐 更多相似问题