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.

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.

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


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.

  • Find the Smallest and Largest Elements: Use the min() and max() functions to find the smallest and largest elements.
  • Filter the Array: Use the array_filter() function to remove the smallest and largest elements from the 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 [];
      }

      $minVal = min($arr);
      $maxVal = max($arr);
      // Filter out the smallest 
     // and largest elements
      $res = array_filter($arr, 
          function($val) use ($minVal, $maxVal) {
          return $val !== $minVal && $val !== $maxVal;
      });

      return array_values($res);
  }

  // Driver code
  $arr = [5, 2, 8, 1, 3, 7];
  $res = removeSmallLarge($arr);
  print_r($res);

?>

Output
Array
(
    [0] => 5
    [1] => 2
    [2] => 3
    [3] => 7
)

Contact Us