OneBite.Dev - Coding blog in a bite size

Find The Minimum And Maximum Element In An Array In PHP

Code snippet for how to Find The Minimum And Maximum Element In An Array In PHP with sample and detail explanation

Working with arrays is a common task in PHP coding. Sometimes, you may need to find the minimum and maximum elements in an array. This article walks you through the process.

Code snippet for finding Minimum and Maximum element in an array

The following PHP function will help you find the maximum and minimum values from an array.

<?php
  $arr = array(1, 2, 3, 4, 5);
  
  // Finding the minimum element
  echo "Minimum Element is: ". min($arr). "\n";

  // Finding the maximum element
  echo "Maximum Element is: ". max($arr);
?>

Code Explanation for finding Minimum and Maximum element in an array

Firstly, we define an array $arr with some integer values.

   $arr = array(1, 2, 3, 4, 5);

To find out the minimum value in this array, we use min() function which is a built-in PHP function. It takes the array as an argument and returns the smallest value.

   echo "Minimum Element is: ". min($arr). "\n";   

Similarly, to get the maximum value from the same array, we use max(). It is also a PHP built-in function that takes an array and returns the largest value in that array.

  echo "Maximum Element is: ". max($arr);  

The complete code, when executed, will output the minimum and the maximum elements from the array respectively. It’s a straightforward and highly useful way to quickly find these values in an array using PHP. Code effectiveness and simplicity are always important and using these in-built PHP functions allows you to achieve that in your script.

php