How to choose the highest value of an array?

Asked

Viewed 2,493 times

13

I’m trying to use the function max, but I can’t hit.

// 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 is. Due to a inexplicable error I received some wrong outputs and created the question, and from some tips I found that it was working (ok, it’s confusing, but what matters is that it’s working). The hypothesis with ksortalso works for the same purpose, so I chose it as solved)

But the exit from var_dump of $saldev after sending the form with the completed fields, is:

array(5) { [0]=> string(0) "" 1=> string(0) "" [2]=> string(0) "" [3]=> string(0) "" [4]=> string(0) "" }

And that of $saldev2 is:

string(0) ""

The HTML of form is within a large table, I will include one of the fields input (everyone is like that):

<label for="Cvpos5"></label>
<input type="text" id="Cvpos5" name="Tdate5" size="10" class="preco"> 

3 answers

8


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

Use krsort to sort the array downwards and just use Current to retrieve the first element, because krsort maintains the correlation between the keys and the values.

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

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

Output:

Tdate21

4

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

$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);

2

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

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

Also, make sure 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"], that besides being less recommended in most cases would not work ever using $_POST.

Example:

<form method="post">

If it still doesn’t work, post the form and the Urls used, but in my experience this should solve..

Browser other questions tagged

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