當前位置:
首頁 > 知識 > php中的幾種輸出方式——printf、sprintf

php中的幾種輸出方式——printf、sprintf

printf

printf函數輸出格式化的字元串

printf(format,arg1,arg2++)

print(format:格式化的字元串,arg為若干個參數)

$num=5;

$location="樹上";

$format="有%d只猴子在%s";

printf($format,$num,$location);

1

2

3

4

輸出結果:有5隻猴子在樹上

$format="有%f只猴子在%s";

1

輸出結果:有5.000000隻猴子在在樹上(%f 顯示關於浮點數)

$format="有%.2f只猴子在%s";(%.2f取小數點後兩位)

1

輸出結果::有5.00隻猴子在在樹上

注%一定要是半形。

經常使用的%:

%d 顯示包含正負號的十進位(負數,0,正數)。

%s 顯示字元串

%f 顯示關於浮點數

sprintf

sprintf($format,$num,$location);

1

輸出結果:沒有輸出(sprintf不做任何輸出)

綜上所述:printf有輸出,sprintf沒有輸出,但是可以返回結果

為了解決這個問題,可以採用以下的方式

$num = 5;

$location = "樹上";

$format = "有%d只猴子在%s";//格式化字元串

$str = sprintf($format,$num,$location);

echo $str;

1

2

3

4

5

輸出結果:有5隻猴子在樹上(把sprintf放到變數里,輸出變數)

也可以這樣改

$num = 5;

$location = "樹上";

$format = "有%d只猴子在%s";//格式化字元串

echo sprintf($format,$num,$location);

1

2

3

4

輸出結果:有5隻猴子在樹上

php中的幾種輸出方式——printf、sprintf

打開今日頭條,查看更多精彩圖片
喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

監控管理之Spring Boot Admin使用
再談前後端API簽名安全?

TAG:程序員小新人學習 |