0
0
PHPprogramming~20 mins

Array unique and flip in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Unique and Flip Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
?>
AArray ( [apple] => 0 [banana] => 1 [orange] => 3 )
BArray ( [0] => apple [1] => banana [3] => orange )
CArray ( [apple] => 2 [banana] => 4 [orange] => 3 )
DArray ( [apple] => 0 [banana] => 2 [orange] => 3 )
Attempts:
2 left
💡 Hint
Remember that array_unique keeps the first occurrence of each value and array_flip swaps keys and values.
Predict Output
intermediate
1: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);
?>
A6
B4
C3
D5
Attempts:
2 left
💡 Hint
Count unique values before flipping.
🔧 Debug
advanced
2: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);
?>
AArray ( [x] => c [y] => c )
BArray ( [x] => b [y] => c )
CWarning: array_flip(): Can only flip STRING and INTEGER values!
DArray ( [x] => b [y] => c ) but keys overwritten silently
Attempts:
2 left
💡 Hint
Check what happens when array_flip has duplicate values in the original array.
📝 Syntax
advanced
1:00remaining
Syntax error in array_unique usage
Which option contains a syntax error when trying to get unique values from an array?
A$unique = array_unique arr;
B$unique = array_unique($arr);
C$unique = array_unique($arr, SORT_STRING);
D$unique = array_unique($arr, SORT_REGULAR);
Attempts:
2 left
💡 Hint
Check the function call syntax carefully.
🚀 Application
expert
2: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);
?>
AArray ( [red] => 0 [blue] => 1 [green] => 2 )
BArray ( [red] => 3 [blue] => 5 [green] => 7 )
CArray ( [red] => 2 [blue] => 5 [green] => 7 )
DArray ( [2] => red [5] => blue [7] => green )
Attempts:
2 left
💡 Hint
array_unique keeps the first key for each unique value. array_flip swaps keys and values.