PHP生成偶数循环问题求助:如何正确使用循环双条件
Hey there! Let's break down why your current loops aren't working and fix them to output the even numbers you want (1-10, so that's 2,4,6,8,10).
First, let's look at why your original code didn't work
Your first for loop:
for($i=0;$i<10 && $i % 2===0;$i++) echo $i;
The problem here is that the loop's condition $i < 10 && $i % 2 === 0 requires both conditions to be true to keep looping. When $i starts at 0, it works (outputs 0), then $i increments to 1. Now $i % 2 === 0 is false, so the loop stops immediately—you never get to check numbers like 2, 4, etc.
Your do-while loop has a similar issue plus a timing problem:
$i=0; do echo $i; while($i++<10 && $i % 2 ==0);
Do-while runs the code first, then checks the condition. You echo 0, then $i increments to 1. Now the condition checks 1 < 10 && 1 % 2 == 0—the second part is false, so the loop stops. You also have a confusion with $i++ (post-increment means the check uses the old value, but the $i % 2 uses the new value, making the logic messy).
Here are the correct ways to do it
Option 1: Loop through all numbers, check for evenness (most straightforward for beginners)
This loops through every number in your range, and only outputs the ones that are even:
// For 1 to 10 for ($i = 1; $i <= 10; $i++) { if ($i % 2 === 0) { // Check if the number is even echo $i . ' '; } } // Output: 2 4 6 8 10
Option 2: Skip odd numbers entirely (more efficient)
Instead of checking every number, start at the first even number in your range and increment by 2 each time—this way you only ever hit even numbers:
// Start at 2 (first even number in 1-10), increment by 2 until we exceed 10 for ($i = 2; $i <= 10; $i += 2) { echo $i . ' '; } // Output: 2 4 6 8 10
If you wanted to include 0 (like your original code tried), just start at 0 instead of 2.
Option 3: Correct do-while version
If you prefer do-while, here's how to write it properly:
$i = 2; do { echo $i . ' '; $i += 2; // Jump to next even number } while ($i <= 10); // Output: 2 4 6 8 10
Or if you want to loop through all numbers and check:
$i = 1; do { if ($i % 2 === 0) { echo $i . ' '; } $i++; } while ($i <= 10);
Key takeaway
The mistake in your original code was putting the "even number check" in the loop's termination condition—this makes the loop stop as soon as it hits an odd number. Instead, use the termination condition only to control the range of numbers, and either check for evenness inside the loop, or adjust your increment step to only generate even numbers.
内容的提问来源于stack exchange,提问作者Stoyan Vatsev

