0

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);
}
asked Mar 5, 2014 at 2:04
10
  • you want to count all value? Commented Mar 5, 2014 at 2:05
  • No i just want to display the maximum value so I used max() but it doesn't echo anything. Any ideas why and how? Commented Mar 5, 2014 at 2:06
  • becuse its inside the loop, and you could just get it from the db rather thing get all rows for this one value Commented Mar 5, 2014 at 2:06
  • $row is a single row, so $row['startShift'] is not an array. Why not stick max in the query? Commented Mar 5, 2014 at 2:07
  • 2
    Why not have MySQL handle your data for you, rather than pulling back results you don't want? SELECT MAX(startShift) FROM seats WHERE seitid = @seat_id" ? Commented Mar 5, 2014 at 2:10

1 Answer 1

2

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
4
  • Im sorry im just a beginner in PHP but can i ask one stupid question? What is $maxStartShift = -INF? and what it's for? Commented Mar 5, 2014 at 2:17
  • 1
    INF is a php constant representing "infinity". If you don't give $maxStartShift a very low initial value, the greater-than comparison might not work. Commented 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? Commented 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. Commented Mar 5, 2014 at 2:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.