Select higher PHP value

Asked

Viewed 953 times

3

I got the following:

$gols = array("Kraken"=>"25",        "Cleiton.Xavier"=>"10",     "Buffon"=>"0",

I wanted to find the greatest value of $gols and the name of the player also as I do?

3 answers

3

Use the function max() that return the highest value and array_search() to search the array for the name of who has this number of goals.

Example:

$gols = array("Kraken"=>"25",        "Cleiton.Xavier"=>"10",     "Buffon"=>"50");

$maiorGol  = max($gols); *//Retorna 50*
$maiorNome = array_search ($maiorGol,$gols); *//Retorna Buffon*
  • 2

    Thank you very much, that’s exactly what I needed.

  • Not at all, Thiago!

  • right that comment right there

2


You can use the function arsort PHP to order the array $gols and so seek the first value of it, which will be the greatest. Try so:

$gols = [
    "Kraken" => "25"
    "Cleiton.Xavier" => "10",
    "Buffon" => "50"
];

arsort($gols);
var_dump($gols);

Returns:

array(3) { ["Buffon"]=> string(2) "50" ["Kraken"]=> string(2) "25" ["Cleiton.Xavier"]=> string(2) "10" }

Now you have in the first index of the array the person with the highest number of goals.

0

To return higher value -> function max()

$gols = array("Pequnion"=>"25","Minimion"=>"10","Zeron"=>"0","Grandon"=>"100","Medion"=>"50");

echo max($gols);

$maxs = array_keys($gols, max($gols));

echo ($maxs[0]);
Para retornar a chave do maior valor, uso array_keys
pois pode haver vários valores máximos iguais 

Example in ideone with two equal maximum values

array_keys - the keys of the positions where a given value is.

example:

$arr = array("determinado valor", "um valor", "outro valor", "determinado valor", "determinado valor");
var_dump(array_keys($arr, "determinado valor));

returns

array(3) {
  [0]=>
  int(0)
  [1]=>
  int(3)
  [2]=>
  int(4)
}

Because "determinado valor" is present at positions 0, 3 and 4 of the array.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.