How to usesort() and array_shift()/array_pop() functions in PHP
The first approach involves sorting the array and removing the first and last elements using array_shift() and array_pop() functions.
- Sort the array: Use the sort() function to sort the array in ascending order.
- Remove the Smallest Element: Use the array_shift() function to remove the first element (smallest element) of the sorted array.
- Remove the Largest Element: Use the array_pop() function to remove the last element (largest element) of the sorted array.
Example: This example shows the implementation of the above-explained approach.
<?php
function removeSmallLarge($arr) {
if (count($arr) <= 2) {
// If array has 2 or fewer elements,
// return an empty array
return [];
}
// Sort array in ascending order
sort($arr);
// Remove the smallest element
array_shift($arr);
// Remove the largest element
array_pop($arr);
return $arr;
}
// Driver code
$arr = [5, 2, 8, 1, 3, 7];
$res = removeSmallLarge($arr);
print_r($res);
?>
Output: