Bird
0
0

You want to create an indexed array of the first 5 positive integers using a loop. Which code correctly does this?

hard📝 Application Q8 of 15
PHP - Arrays
You want to create an indexed array of the first 5 positive integers using a loop. Which code correctly does this?
A$arr = array(); for ($i = 0; $i < 5; $i++) { $arr[$i] = $i; }
B$arr = []; for ($i = 1; $i <= 5; $i++) { $arr[] = $i; }
C$arr = []; for ($i = 1; $i < 5; $i++) { $arr[$i] = $i; }
D$arr = array(); for ($i = 1; $i <= 5; $i++) { $arr[$i] = $i; }
Step-by-Step Solution
Solution:
  1. Step 1: Understand loop and array appending

    Using $arr[] = $i; appends $i to the end of the array with automatic indexing starting at 0.
  2. Step 2: Check loop range and array filling

    The loop runs from 1 to 5 inclusive, adding values 1 through 5 to the array.
  3. Final Answer:

    $arr = []; for ($i = 1; $i <= 5; $i++) { $arr[] = $i; } -> Option B
  4. Quick Check:

    Appending with [] in loop = $arr = []; for ($i = 1; $i <= 5; $i++) { $arr[] = $i; } [OK]
Quick Trick: Use $arr[] = value to append in loops [OK]
Common Mistakes:
  • Using wrong loop bounds
  • Assigning to $arr[$i] starting at 1 causing gaps
  • Not appending properly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes