Bird
0
0

What will be the output of the following PHP code?

medium📝 Predict Output Q13 of 15
PHP - Arrays
What will be the output of the following PHP code?
$arr = [3 => 'apple', 1 => 'banana', 2 => 'cherry'];
sort($arr);
print_r($arr);
A[0 => 'apple', 1 => 'banana', 2 => 'cherry']
B[1 => 'banana', 2 => 'cherry', 3 => 'apple']
C[0 => 'banana', 1 => 'cherry', 2 => 'apple']
D[0 => 'apple', 1 => 'cherry', 2 => 'banana']
Step-by-Step Solution
Solution:
  1. Step 1: Understand sort() behavior on keys

    sort() sorts values ascending and resets keys starting from 0.
  2. Step 2: Sort values and assign new keys

    Values sorted ascending: 'apple', 'banana', 'cherry'. Keys reset to 0,1,2 respectively.
  3. Final Answer:

    [0 => 'apple', 1 => 'banana', 2 => 'cherry'] -> Option A
  4. Quick Check:

    sort() resets keys and sorts ascending [OK]
Quick Trick: sort() resets keys and sorts values ascending [OK]
Common Mistakes:
  • Expecting original keys to remain
  • Confusing sort() with asort()
  • Mixing order of sorted values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes