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);
}
1 Answer 1
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.
answered Mar 5, 2014 at 2:08
-
Im sorry im just a beginner in PHP but can i ask one stupid question? What is $maxStartShift = -INF? and what it's for?rez– rez03/05/2014 02:17:54Commented Mar 5, 2014 at 2:17
-
1INF is a php constant representing "infinity". If you don't give
$maxStartShift
a very low initial value, the greater-than comparison might not work.Jorg– Jorg03/05/2014 02:29:49Commented Mar 5, 2014 at 2:29 -
I have one more favor to ask. If want the minimum value now, how should I go on about this?rez– rez03/05/2014 02:39:37Commented Mar 5, 2014 at 2:39
-
1@rez You do the same thing but in reverse; you start with a value of
INF
and then compare if anything is lower than the current minimum.Ja͢ck– Ja͢ck03/05/2014 02:44:12Commented Mar 5, 2014 at 2:44
lang-php
$row
is a single row, so$row['startShift']
is not an array. Why not stickmax
in the query?