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
<?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:


Remove Smallest and Largest Elements from PHP Array

In this article, we will learn how to remove the smallest and largest elements from an array in PHP. Handling arrays is a common task in PHP. We will cover various approaches to remove the smallest and largest elements from an array in PHP.

Similar Reads

Approach 1: Using sort() and array_shift()/array_pop() functions

The first approach involves sorting the array and removing the first and last elements using array_shift() and array_pop() functions....

Approach 2: Using max(), min(), and array_filter() functions

This approach uses the PHP max(), min(), and array_filter() functions to remove the smallest and largest elements without sorting the array....