rez
rez

Reputation: 49

Max value of an array in PHP

Why isn't this working? Is there something wrong with my syntax or anything? I want to echo the max value of the $row2['startShift'] array but it displays nothing.

$query2 = "SELECT startShift,endShift from seats where seatid=".$row['seatid'];
$result2 = mysql_query($query2);

while ($row2 = mysql_fetch_array($result2)){
    $startShift = $row2['startShift'];
    echo max($startShift);
}

Upvotes: 0

Views: 72

Answers (1)

Ja͢ck
Ja͢ck

Reputation: 173542

You calculate a maximum by keeping a separate variable outside of the loop:

$maxStartShift = -INF;
while ($row2 = mysql_fetch_array($result2)){
    if ($row2['startShift'] > $maxStartShift) {
        $maxStartShift = $row2['startShift'];
    }
    echo $maxStartShift; // maximum until now
}

The max() function returns the maximum value of it's arguments, so max(1, 2) == 2 or max([1, 2]) == 2. In your case:

echo max($row2['startShift']);

Will just return $row2['startShift'] because that's the maximum of all arguments passed to the function.

Upvotes: 2

Related Questions