+

PHP program for finding maximum and minimum in an array

Examples:
Input: arr [] = {2, 3, 1, 6, 7} Output: Maximum integer of the given array: 7 Minimum integer of the given array: 1 Input: arr [] = {1, 2, 3, 4, 5} Output: Maximum integer of the given array: 5 Minimum integer of the given array: 1 
Approach 1 (simple ):we just loop through the array, find its maximum and minimum.
// Returns the maximum in the array function getMax ( $array ) { $n = count ( $array ); $max = $array [0]; for ( $i = 1; $i < $n ; $i ++) if ( $max < $array [ $i ]) $max = $array [ $i ]; return $max ; }  
// Returns the maximum in the array function getMin ( $array ) { $n = count ( $array ); $min = $array [0]; for ( $i = 1; $i < $n ; $i ++) if ( $min > $array [ $i ]) $min = $array [ $i ]; return $min ; }  
// Driver code $array = array (1, 2, 3, 4, 5); echo (getMax ( $array )); echo ( "" ); echo (getMin ( $array )); ?>
Output:
5 1 
Approach 2 (Using library functions):we use library functions to find the minimum and maximum.
  • Max():max() returns the parameter value that is considered the “highest” according to standard comparisons. If multiple values ​​of different types evaluate to equal (for example, 0 and "abc"), the first value supplied to the function will be returned.
  • Min():min() returns the parameter value which is considered “lowest” according to standard comparisons. If multiple values ​​of different types evaluate to equal (for example, 0 and "abc"), the first value supplied to the function will be returned.
  • < ? php $array = array (1, 2, 3, 4, 5); echo (max ( $array )); echo ( "" ); echo (min ( $array )); ?> Output:
    5 1 
    Get Solution for free from DataCamp guru