PHP开发:按15递增计数(上限45)及用for循环计算军事时间间隔数
Hey there! Let's break down your two PHP problems step by step with practical, easy-to-follow code examples.
Requirement 1: Count Up by 15, Max Value 45
This is super straightforward with a for loop. We just set our starting value, increment by 15 each iteration, and stop when we hit 45. Adjust the starting number if you don't want to begin at 0:
// Start at 0, count up to 45 in 15-increment steps for ($count = 0; $count <= 45; $count += 15) { echo $count . " "; // Output: 0 15 30 45 } // If you want to start at 15 instead: // for ($count = 15; $count <= 45; $count += 15) { // echo $count . " "; // Output: 15 30 45 // }
The loop works by initializing $count to your starting number, checking if it’s still ≤ 45, running the code inside, then adding 15 to $count each time until the condition fails.
Requirement 2: Calculate 15-Minute Blocks Between Military Times Using a For Loop
First, we need to convert those 4-digit military time strings (like "0930") into total minutes since midnight—this makes math and looping way simpler. Then we can use a for loop to iterate through each 15-minute interval and count the blocks.
Step 1: Helper Function to Convert Military Time to Minutes
Let’s write a quick function to turn a military time string into minutes:
function militaryToMinutes($time) { // Split the 4-digit string into hours and minutes $hours = (int)substr($time, 0, 2); $minutes = (int)substr($time, 2, 2); return $hours * 60 + $minutes; }
Step 2: Use a For Loop to Count Blocks
Now we can take our start and end times, convert them, then loop through each 15-minute slot:
$startTime = "0900"; $endTime = "1115"; $startMins = militaryToMinutes($startTime); $endMins = militaryToMinutes($endTime); $blockCount = 0; // Loop from start time to end time, incrementing by 15 minutes each time for ($currentMins = $startMins; $currentMins < $endMins; $currentMins += 15) { $blockCount++; } echo "Total 15-minute blocks: " . $blockCount; // Output: 9 for 0900→1115
Quick Note on Your Example:
You mentioned 0900 to 1115 should be 8 blocks, but mathematically that’s 2 hours and 15 minutes (135 minutes), which divides into 9×15-minute slots. The code above correctly returns 9 here. Your second example (1130→1430) will return 12 blocks, which matches your expectation—perfect!
Edge Cases to Handle:
- If
$startTimeequals$endTime, the loop won’t run, so$blockCountstays 0 (correct, since there are no blocks between the same time). - If you might pass an end time earlier than the start time, add a quick swap check:
if ($startMins > $endMins) { [$startMins, $endMins] = [$endMins, $startMins]; }
内容的提问来源于stack exchange,提问作者BostonPHPGuy

