2011-03-31 9 views
2

標準の数字として8桁の数字を作る方法。番号はデータベースからのユーザーIDになります。 例PHPの8桁の数字の質問

user_id = 1 // This should should be echo as 00000001 
user_id = 11 // This should should be echo as 00000011 
user_id = 111 // This should should be echo as 00000111 

どうすればよいですか?ありがとうございました。

答えて

2

あなたはフォーマット文字列として%08sprintf機能を使用することができます。

printf("%08s",$user_id); 

あなたが戻って文字列に結果を保存したい場合は、としてsprintfを使用することができます。

$user_id = sprintf("%08s",$user_id); 

書式指定子%08sさんのコメント:

s : Interpret the argument as a string 
8 : Print the string left justified within 8 alloted places 
0 : Fill the unused places with 0 
2

あなたはprintfを使用することができます。

printf("%08d", $user_id); 
+0

ありがとうございます:) – Jorge

0

$ USER_ID = str_pad($ user_idは、8、 "0"、STR_PAD_LEFT)。

2

PHPはsprintfを持っている:あなたはstr_pad

echo str_pad($user_id,8,'0',STR_PAD_LEFT); 
2

0
function leadingZeroes($number, $paddingPlaces = 3) { 
    return sprintf('%0' . $paddingPlaces . 'd', $number); 
} 

Sourceで行うことができます

$user_str = sprintf("%08d", $user_id); 
echo $user_str;