PHP - LoopsYou want to print all even numbers from 2 to 10 using a PHP for loop. Which code correctly does this?Afor ($i = 2; $i < 10; $i += 2) { echo $i . ' '; }Bfor ($i = 0; $i <= 10; $i += 2) { echo $i . ' '; }Cfor ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . ' '; }Dfor ($i = 2; $i < 10; $i++) { if ($i % 2 == 0) echo $i . ' '; }Check Answer
Step-by-Step SolutionSolution:Step 1: Understand the goalWe want to print even numbers from 2 to 10 inclusive.Step 2: Check each optionfor ($i = 2; $i < 10; $i += 2) { echo $i . ' '; } prints 2 4 6 8, missing 10. for ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . ' '; } loops 1 to 10 and prints only even numbers 2 4 6 8 10 correctly. for ($i = 2; $i < 10; $i++) { if ($i % 2 == 0) echo $i . ' '; } stops at 9, missing 10. for ($i = 0; $i <= 10; $i += 2) { echo $i . ' '; } starts at 0, which is not in the range 2 to 10.Step 3: Choose the best optionfor ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . ' '; } is correct and flexible, printing even numbers by checking inside the loop.Final Answer:for ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . ' '; } -> Option CQuick Check:Loop 1-10, print if even = for ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) echo $i . ' '; } [OK]Quick Trick: Use modulo % to check even numbers inside loop [OK]Common Mistakes:Stopping loop before 10Starting loop at 0 when not neededForgetting to check even condition
Master "Loops" in PHP9 interactive learning modes - each teaches the same concept differentlyLearnWhyDeepVisualTryChallengeProjectRecallTime
More PHP Quizzes Arrays - Array access and modification - Quiz 10hard Conditional Statements - Elseif ladder execution - Quiz 13medium Conditional Statements - Match expression (PHP 8) - Quiz 15hard Functions - Global keyword behavior - Quiz 6medium Functions - Global keyword behavior - Quiz 1easy Functions - Variable scope in functions - Quiz 14medium Functions - Return type declarations - Quiz 6medium Loops - Break statement with levels - Quiz 15hard Operators - Why operators matter - Quiz 6medium Output and String Handling - Printf and sprintf formatting - Quiz 3easy