Raffy T Lawrence
Raffy T Lawrence

Reputation: 355

PHP : How to get the lowest array value together of the key

I have a an array and I need to get the lowest value together of key. Because i need to check if the value has contain the right key or not

 Array ( 
      [120] => 97.00 
      [132] => 92.67 
      [124] => 72.33 
      [131] => 49.67 
      [129] => 25.00 
      [127] => 25.00 //<--Get the value and this key
  )
  //This array already sorted, no need to sort just get the last value and key

How can i get the lowest value 25.00 together the key [127]

 $array = array (

      "120" => 97.00 
      "132" => 92.67 
      "124" => 72.33 
      "131" => 49.67 
      "129" => 25.00 
      "127" => 25.00 

  );

  print_r(min($array)); //<--displaying only the value but not the key

The output should be like

127 - 25.00

Upvotes: 1

Views: 112

Answers (4)

Shailendra Vasave
Shailendra Vasave

Reputation: 91

$array=array("120" =>97.00 ,"132"=>92.67,"124"=>72.33 ,"131"=>49.67,"129"=>29.00,"127"=> 25.00);
//get minimum value from array
 $minvalue=(min($array));
 echo "Min Value= ".$minvalue;
//get key of minimum value from array
 $key = array_search($minvalue, $array);
  echo "Key of Min Value".$key;
// make new associative array
$newarray = array($key => $minvalue ); 
  print_r($newarray); 

Upvotes: 4

cnizzardini
cnizzardini

Reputation: 1240

PHP manual loaded with good stuff.

Sort: http://php.net/manual/en/function.asort.php

Current: http://php.net/manual/en/function.current.php

Key: http://php.net/manual/en/function.key.php

<?php
 $array = array (
      "120" => 97.00 ,
      "132" => 92.67 ,
      "124" => 72.33 ,
      "131" => 49.67 ,
      "129" => 25.00 ,
      "127" => 25.00 
  );
asort($array);
$key = key($array);
$value = current($array);
echo "$key - $value"; 
?>

You can also use arsort() then do array_pop(). Depends on which direction you want to go.

Upvotes: -1

Veshraj Joshi
Veshraj Joshi

Reputation: 3579

$array = array (
      "120" => 97.00, 
      "132" => 92.67,
      "124" => 72.33,
      "131" => 49.67,
      "129" => 25.00,
      "127" => 25.00 

  );
    // point the last element of the element and fetch value to $value
    $value= (end($array));
    // fetch key
    echo "key : ". key($array);
    echo "value :".$value;

Upvotes: 1

Amit.S
Amit.S

Reputation: 441

Try using asort and then get the key and value of first element

//using asort will preserve key value pair sort will happen on value
asort($urarray);
foreach($urarray as $k=>$val){
   //read the first element and break
   echo $k.' - '.floatval($val);
   break;
}

For more information on asort read this php asort

Upvotes: 0

Related Questions