Challenge - 5 Problems
Array Unique and Flip Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of array_unique and array_flip combination
What is the output of the following PHP code?
PHP
<?php $arr = ['apple', 'banana', 'apple', 'orange', 'banana']; $result = array_flip(array_unique($arr)); print_r($result); ?>
Attempts:
2 left
💡 Hint
Remember that array_unique keeps the first occurrence of each value and array_flip swaps keys and values.
✗ Incorrect
array_unique removes duplicate values but keeps the first key for each unique value. Then array_flip swaps keys and values, so the unique values become keys and their original keys become values.
❓ Predict Output
intermediate1:30remaining
Count of items after array_unique and array_flip
How many items are in the resulting array after running this code?
PHP
<?php $input = ['cat', 'dog', 'cat', 'bird', 'dog', 'fish']; $output = array_flip(array_unique($input)); echo count($output); ?>
Attempts:
2 left
💡 Hint
Count unique values before flipping.
✗ Incorrect
array_unique removes duplicates, leaving ['cat', 'dog', 'bird', 'fish'] which is 4 items. array_flip does not change the count.
🔧 Debug
advanced2:00remaining
Identify the error in array_flip usage
What error will this PHP code produce?
PHP
<?php $arr = ['a' => 'x', 'b' => 'x', 'c' => 'y']; $result = array_flip($arr); print_r($result); ?>
Attempts:
2 left
💡 Hint
Check what happens when array_flip has duplicate values in the original array.
✗ Incorrect
array_flip swaps keys and values. If values are duplicated, the last key overwrites previous ones silently. So 'x' maps to 'b' (last key with value 'x').
📝 Syntax
advanced1:00remaining
Syntax error in array_unique usage
Which option contains a syntax error when trying to get unique values from an array?
Attempts:
2 left
💡 Hint
Check the function call syntax carefully.
✗ Incorrect
Option A misses parentheses around the argument, causing a syntax error.
🚀 Application
expert2:30remaining
Result of combined array_unique and array_flip with numeric keys
Given the code below, what is the output?
PHP
<?php $input = [2 => 'red', 5 => 'blue', 3 => 'red', 7 => 'green']; $output = array_flip(array_unique($input)); print_r($output); ?>
Attempts:
2 left
💡 Hint
array_unique keeps the first key for each unique value. array_flip swaps keys and values.
✗ Incorrect
array_unique keeps the first occurrence of 'red' at key 2, so unique array is [2=>'red',5=>'blue',7=>'green']. array_flip swaps keys and values, so 'red' => 2, 'blue' => 5, 'green' => 7.