-2

I'm trying to get the key and value of an array which has min value. Here is my code. I have empty value variables I want the values which are not empty and from the values, i need a key and the value which is min from an array or any other mode if possible.

 <?php
      $serial_sale_price    ='2';
        $promo_sale_price   ='';
        $inv_sale_price     ='300.00';
        $price_search_seq = 'B';
        //validate for 0 values
        if($serial_sale_price!='' && $serial_sale_price==0)
        {
            $serial_sale_price='0.00';
        }
        if($promo_sale_price!='' && $promo_sale_price==0)
        {
            $promo_sale_price='0.00';
        }
        if($inv_sale_price!='' && $inv_sale_price==0)
        {
            $inv_sale_price='0.00';
        }


        $remove_empty = array('S'=>$serial_sale_price,
                               'P'=>$promo_sale_price, 
                               'I'=>$inv_sale_price);
        $find_min = array_filter($remove_empty); // Array which required in 
        echo "<pre>";
        print_r($find_min);
        $sale_price =  min($find_min);//Minimum Price for the array 
        $price_rule = '';//here i want to get the key which have min value

        echo "sales price:$sale_price,price_rule:$price_rule";

How to get the key of min value and key of the min value at a time. what i'm expecting from my example. if min value is serial_sales_price then key is 'S' and value is 2

vijay kumar
  • 287
  • 2
  • 8
  • 28
  • Please learn to do basic research - typing "php array get min and key" into Google was enough to find this. – CBroe Dec 02 '17 at 05:12

1 Answers1

0
// Sample by PHP Method 

$var = array_keys($remove_empty , min($remove_empty ));
//$var[0] for letest key have minimum value.    

//This function returns the key for the minimum value. 

function getMinKey( $array )
{
    $min = 0;
    $key = '';
    foreach( $array as $k => $v )
    {
        $min = min($array);
    }
    foreach( $array as $k => $v )
    {

        if($min == $v)
        {
            $key = $k;
        }


    }
    return $key;
}

  echo getMinKey($remove_empty); // for min value key; 
A.D.
  • 2,352
  • 2
  • 15
  • 25