如何使用PHP生成含当前日期与用户输入的10位指定格式数字
Got it, let's break down how to create this 10-digit number exactly as you need it:
First, let's recap the requirements to make sure we're aligned:
We need a 10-digit string made by combining:
- The current date in
yymmddformat (e.g., 2018-04-30 becomes180430)- The user's input, padded with leading zeros to make it 4 digits (e.g., input
1becomes0001, input12becomes0012)
Step-by-Step Solution
Format the date correctly
Use PHP'sdate()function with theymdformat specifier—this directly gives us the 6-digityymmddstring we need. No need to start withY-m-dand reformat it later!Pad the user input to 4 digits
Thesprintf()function is perfect for this. Using%04das the format string will take any integer input and pad it with leading zeros until it's 4 characters long. Even if the user enters a string (like"12"), it'll get converted to a number and padded correctly.Combine the two parts
Just concatenate the formatted date string and the padded input string to get your 10-digit result.
Full Code Example
// Get current date in yymmdd format (6 digits) $formatted_date = date('ymd'); // User input example (can be integer or string) $user_input = 1; // Pad user input to 4 digits with leading zeros $padded_input = sprintf('%04d', $user_input); // Combine to get the 10-digit output $output = $formatted_date . $padded_input; // Output: 1804300001 (matches your example!) echo $output;
Quick Notes
- If you need the result as an integer instead of a string, you can cast it with
(int)$output—but keep in mind that leading zeros in the input part would be lost if you do this. For most use cases (like IDs or display), keeping it as a string is safer. - If the user input could be non-numeric, you might want to add validation (like
is_numeric($user_input)) to avoid unexpected results.
内容的提问来源于stack exchange,提问作者user5443928

