0
0
PHPprogramming~20 mins

Array sort functions in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Array Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using sort()?
Consider the following PHP code snippet. What will be the output after sorting the array with sort()?
PHP
<?php
$arr = [3, 1, 4, 1, 5];
sort($arr);
print_r($arr);
?>
AArray ( [0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 1 )
BArray ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )
CArray ( [0] => 3 [1] => 1 [2] => 4 [3] => 1 [4] => 5 )
DArray ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 )
Attempts:
2 left
💡 Hint
sort() sorts the array in ascending order and reindexes the keys.
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using asort()?
Look at this PHP code. What will be printed after using asort() on the array?
PHP
<?php
$arr = [3 => 'apple', 1 => 'banana', 2 => 'cherry'];
asort($arr);
print_r($arr);
?>
AArray ( [3] => apple [2] => cherry [1] => banana )
BArray ( [1] => banana [3] => apple [2] => cherry )
CArray ( [3] => apple [1] => banana [2] => cherry )
DArray ( [2] => cherry [1] => banana [3] => apple )
Attempts:
2 left
💡 Hint
asort() sorts values but keeps original keys.
Predict Output
advanced
2:00remaining
What is the output of this PHP code using krsort()?
What will be the output after sorting the array by keys in descending order using krsort()?
PHP
<?php
$arr = ['a' => 3, 'c' => 1, 'b' => 2];
krsort($arr);
print_r($arr);
?>
AArray ( [b] => 2 [c] => 1 [a] => 3 )
BArray ( [a] => 3 [b] => 2 [c] => 1 )
CArray ( [c] => 3 [b] => 2 [a] => 1 )
DArray ( [c] => 1 [b] => 2 [a] => 3 )
Attempts:
2 left
💡 Hint
krsort() sorts keys in reverse (descending) order.
Predict Output
advanced
2:00remaining
What error does this PHP code raise when using usort() incorrectly?
What error will this PHP code produce?
PHP
<?php
$arr = [3, 1, 4];
usort($arr, 'nonexistent_function');
print_r($arr);
?>
AWarning: usort() expects parameter 2 to be a valid callback, function 'nonexistent_function' not found
BFatal error: Call to undefined function nonexistent_function()
CArray ( [0] => 1 [1] => 3 [2] => 4 )
DParse error: syntax error, unexpected 'usort'
Attempts:
2 left
💡 Hint
usort() requires a valid callback function name as second argument.
🧠 Conceptual
expert
2:00remaining
How many items are in the array after this PHP code runs?
Given this PHP code, how many items will the array contain after sorting?
PHP
<?php
$arr = [0 => 'zero', 1 => 'one', 2 => 'two'];
array_splice($arr, 1, 1);
sort($arr);
print_r($arr);
?>
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
array_splice removes one element at index 1, then sort reindexes the array.