How to choose the largest value of an array?

13

I'm trying to use the max function, but I can not get it right.

// variáveis da diferença salarial 
$saldev[0] = $_POST ["Tdate5"];
$saldev[1] = $_POST ["Tdate9"];
$saldev[2] = $_POST ["Tdate13"];
$saldev[3] = $_POST ["Tdate17"];
$saldev[4] = $_POST ["Tdate21"];

$saldev2 = max($saldev);

(Note: The above code works the way it looks.) Due to a

asked by anonymous 21.04.2015 / 06:44

3 answers

8

There is a function to sort an array by keys in descending order - krsort

Use krsort to sort the array in a decreasing way and just use current to retrieve the first element, since krsort maintains the correlation between the keys and values.

$saldev[] = 'Tdate5';
$saldev[] = 'Tdate9';
$saldev[] = 'Tdate13';
$saldev[] = 'Tdate17';
$saldev[] = 'Tdate21';

krsort($saldev);
echo current( $saldev );

Output:

Tdate21
    
21.04.2015 / 10:26
4

The max function expects to receive an array of numbers, so do this:

$saldev[0] = (double) $_POST ["Tdate5"];
$saldev[1] = (double) $_POST ["Tdate9"];
$saldev[2] = (double) $_POST ["Tdate13"];
$saldev[3] = (double) $_POST ["Tdate17"];
$saldev[4] = (double) $_POST ["Tdate21"];

$saldev2 = max($saldev);
    
22.04.2015 / 01:59
2

There is a space in your line, the bracket should "lean" on the variable:

$saldev[0] = $_POST["Tdate5"];

In addition, make sure that the form contains method="post" or it will send the data by GET . When sent by GET the values are accessible via something like $_GET["Tdate5"] , which in addition to being less recommended in most cases would never work using $_POST .

Example:

<form method="post">

If it still does not work, post the form and the URLs used, but from my experience this should resolve ..

    
21.04.2015 / 09:56