LoginSignup
5
6

More than 5 years have passed since last update.

PHP printf() 関数

Posted at

printf()関数

printf()
書式(フォーマット)を整える。
様々な指定に合わせて書式を整えることが出来る関数。

printf( 書式文字列(型変換指定子, 可変個引数 );

▪️可変引数(or可変個引数)
任意の個数となっている引数

------------------------------------------------------------------------------------------
▪️test1.php 例①

<!-- http://localhost:8888/sample3/test01.php -->
<?php
$date = sprintf ( '%04d年 %02d月 %02d日', 2010, 1, 23 );
?>
<?php

print ($date) ;
?>

▪️test1.php 実行結果
2010年 01月 23日
▪️test1.php 解説
1番目のパラメーターで「%d」などの書式指定を含む出力結果を書き、
2番目以降のパラメーターで、指定に代入したい値を書く。
------------------------------------------------------------------------------------------
▪️test1.php 例②

<?php
$fix = sprintf ( '%s', 10 );
print ($fix) ;
?>

▪️test1.php 実行結果
10
------------------------------------------------------------------------------------------
▪️test1.php 例③

<?php
$fix = sprintf ( '%d', 'abc' );
print ($fix) ;
?>

▪️test1.php 実行結果
0
------------------------------------------------------------------------------------------

▪️test1.php 例③

<?php
$fix = sprintf ( '%s', 'abc' );
print ($fix) ;
?>

▪️test1.php 実行結果
abc
------------------------------------------------------------------------------------------
▪️test1.php 例④

<?php
$fix = sprintf ( '%05d', 10 );
print ($fix) ;
?>

▪️test1.php 実行結果
00010

▪️test1.php 例④ 解説
%05dは、5桁になるまで0を補って数字として整えるという意味。

参考になるページ

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6