PHP輸出函數print, printf, sprintf的區別

來源:互聯網
上載者:User

標籤:兩種   eth   支援   返回   rgs   傳回值   void   類型   uri   

PHP中常用的字串輸出方式是:使用echo和print兩種方法來顯示字串。如果涉及格式化輸出操作,還可以試用printf和sprintf函數。

一、先說echo和print兩種方法

  1. print的文法格式為:int print ( string $arg   )  
  2. echo的文法格式為:void echo ( string $arg1   [, string $...  ] )

echo都是一種類似於函數的輸出方式而非函數,沒有傳回值,且支援多參數;

print是輸出函數,其傳回值為int類型的1,且只支援一個參數。

echo用法即可以用英文逗號","串連多參數,也可以用英文點號"."作為連符組成一個參數,舉個栗子:

echo ‘This ‘, ‘string ‘, ‘was ‘, ‘made ‘, ‘with multiple parameters.‘, chr(10);echo ‘This ‘ . ‘string ‘ . ‘was ‘ . ‘made ‘ . ‘with concatenation.‘ . "\n";

print就不能用上面的英文逗號","串連多參數,只能用英文點號"."作為連符組成一個參數。例如上述第二句用print寫法為:

print(‘This ‘ . ‘string ‘ . ‘was ‘ . ‘made ‘ . ‘with concatenation.‘ . "\n");

二、重點來了,在PHP中sprintf和printf函數都是用來格式化操作字串的,兩者的輸出文法格式分別為:

  1. printf的文法格式為:int printf    ( string $format   [, mixed $args   [, mixed $...  ]] )
  2. sprintf的文法格式為:string sprintf    ( string $format   [, mixed $args   [, mixed $...  ]] )

兩者的區別是:

  1. printf()函數可以直接將格式化之後的字串輸出,而sprintf()函數需要使用echo方法將格式化後的字串輸出。
  2. printf()函數的傳回值為int類型,表示列印出來字串的字元數量,而sprintf()函數的傳回值為一個字串。

舉個例子就都明白了:

<h3>PHP輸出函數print,printf,sprintf的區別</h3>  
<?PHP 
$str=‘This is an example for this.‘; 
echo $str."<br>";     //這裡輸出This is an example for this.
$number=print ($str."<br>");    //這裡輸出This is an example for this.
echo $number."<br>";  //這裡輸出1
$format="%b, %c, %d, %s"; 
$num1=printf($format,65,65,65,65);   //這裡輸出1000001, A, 65, 65
echo "<br>";
echo $num1."<br>";  //這裡輸出18,對應字串的個數
echo sprintf($format,97,97,97,97);  //這裡利用echo輸出1100001, a, 97, 97
?>

 

PHP輸出函數print, printf, sprintf的區別

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.