Bird
0
0

You have an array $arr = ['a', 'b', 'a', 'c', 'b']. How can you create a new array where keys are unique values and values are their original first indexes?

hard📝 Application Q8 of 15
PHP - Array Functions
You have an array $arr = ['a', 'b', 'a', 'c', 'b']. How can you create a new array where keys are unique values and values are their original first indexes?
A$unique = array_unique($arr);
B$unique = array_unique(array_flip($arr));
C$unique = array_flip(array_unique($arr));
D$unique = array_flip($arr);
Step-by-Step Solution
Solution:
  1. Step 1: Remove duplicates keeping first occurrences

    array_unique($arr) removes duplicates, preserving first indexes.
  2. Step 2: Flip keys and values to get unique values as keys and indexes as values

    array_flip() swaps keys and values, so unique values become keys and their original indexes become values.
  3. Final Answer:

    $unique = array_flip(array_unique($arr)); -> Option C
  4. Quick Check:

    array_flip(array_unique()) = unique keys with original indexes [OK]
Quick Trick: Use array_flip(array_unique($arr)) for unique keys with original indexes [OK]
Common Mistakes:
  • Flipping before removing duplicates
  • Using only array_unique() without flipping
  • Flipping without removing duplicates

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes