Tuesday 12 July 2016

Get Maximum Numeric value from Associative Array in PHP

This tutorial cover how can we get the maximum numeric value from associative array in php. First of all what is an associative array in php. Associative array has two field one is key which is an unique and other is value of particular key. Suppose you have work on any project in php and you have fetch data like employee name, gender and it's salary from database and store that data in an associative array and from that array you want to figure out maximum salary of particular employee then at that time you can use this type of code. Here I have make one customize php function for getting maximum  numeric value from Associative array in php. This function only find maximum numeric value not any string value from php Associative array. There are many function available in php for getting maximum value from numeric value but most of all for Index array not specific function for associative array in PHP. You can find the source code in this post and you can also learn from video which I have already attach in this post.

Source Code


 <?php   
 //Get Maximum Numeric value from Associative Array in PHP  
 $employee_array = array(  
   0 => array(  
     'Name'           => 'Jesus H. Duran',  
     'Gender'      => 'Male',  
     'City'          => 'Los Angeles',  
     'Salary'      => '5000'  
   ),  
   1 => array(  
     'Name'           => 'Darryl B. Dealba',  
     'Gender'      => 'Male',  
     'City'          => 'Tampa',  
     'Salary'      => '6000'  
   ),  
   2 => array(  
     'Name'           => 'Louise R. Stone',  
     'Gender'      => 'Female',  
     'City'          => 'Sanford',  
     'Salary'      => '4500'  
   ),  
      3 => array(  
     'Name'           => 'Donald M. Northcutt',  
     'Gender'      => 'Male',  
     'City'          => 'Noxapater',  
     'Salary'      => '7200'  
   ),  
      4 => array(  
     'Name'           => 'Paul S. Gilham',  
     'Gender'      => 'Male',  
     'City'          => 'New York',  
     'Salary'      => '8500'  
   )  
 );  
 function max_array_value($array, $key_name)  
 {  
      $max = '';  
      foreach($array as $key => $value)  
      {  
           if(is_numeric($value[$key_name]))  
           {  
                $make_array[] = $value[$key_name];  
                $max = max($make_array);  
           }  
           else  
           {  
                $max = "This is not Numeric Value";  
           }  
      }  
      return $max;  
 }  
 echo max_array_value($employee_array, 'Salary');  
 ?>  

1 comment:

  1. Super! But how can get another key assoc with max value?
    For example
    Salary is 8500
    City is New York ?

    ReplyDelete