Array Maximum Minimum value

We can calculate maximum value among the elements of an array by using max function. Here is a simple example.
Maximum value of Array
$ar=array(25,26,47,14,29,58,15);
echo max($ar); // output is 58

  • Maximum & Minimum value & key of Array


Another example
$ar=array(1=>15,3=>25,4=>13,5=>10);
echo max($ar);// output is 25

Key of the maximum value in array

To get the key of the maximum value of the array we have to use array_keys function.
We can also search for the value and return the key by using array_search()
$ar=array(1=>15,3=>25,4=>13,5=>10);

echo max($ar); // output 25 
echo "<br>";
$b= array_keys($ar,max($ar));
echo $b[0]; // output 3 

echo "<br>"; // using array_search()
$key=array_search(max($ar),$ar);
echo $key; // output 3
We can use this in string arrays also.
$a=array('Welcome',0);
echo max($a); //optput is Welcome
$ar=array('b','k','l','mz','Ma','na');
echo max($ar); // output is na

Min function

We can use min function also in same way to get the minimum value from the array. Here is the example.
$ar=array(25,26,47,14,29,58,15);
echo min($ar);

Example with two max value

<?Php
$value= array(2,5,6,8,9,4,9,1);
echo "Maximum  value = ".max($value);
?>
Output is
Maximum value = 9

Example

Here is an array of students where name of the student is key and mark is stored as value. Collect the highest and lowest mark ( values here ) along with the student names ( keys here ) . Used array_search() to collect the key ( student name )
$student=array('Ron'=>15,'Geek'=>25,'Alex'=>13,'Ravi'=>14);

echo "highest mark : ". max($student); // output 25
echo "<br>";
echo "Student got highest mark:".array_search(max($student),$student);
echo "<br>";
echo "Lowest mark : ". min($student); // output 13
echo "<br>";
echo "Student got Lowest mark:".array_search(min($student),$student);
Output is here.
highest mark : 25
Student got highest mark : Geek
Lowest mark : 13
Student got Lowest mark : Alex
Joining Two Arrays by array_merge
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    psjlakshmi

    10-11-2014

    if there are duplicate values or if the minimum value is twice in the array?
    smo

    27-03-2015

    example with two maximum value is added

    10-09-2019

    excellent, thank you!

    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer