1

ok so im working with this loop and getting information from DB:

for($i0 = 0; $i0 < $total0; $i0 ++) {
    $id = $oconecta->retrieve_value($i0, "id_tam_product");
    $price = $oconecta->retrieve_value($i0, "price_tam_product");

    echo $id; // RESULTS: 312, 313, 314
    echo $price; // RESULTS: 180.00, 250.00, 300.00
}

i was wondering how can i get the MAX value for that loop:

echo $id; //RESULTS: 314 
echo $price; //RESULTS: 300.00 
2

2 Answers 2

2
$maxID = 0;
$maxPrice = 0;
for($i0=0;$i0<$total0;$i0++)
{
  $id=$oconecta->retrieve_value($i0,"id_tam_product");
  $price=$oconecta->retrieve_value($i0,"price_tam_product");

  $maxID = max($id, $maxID);
  $maxPrice = max($price, $maxPrice);
}

echo "MAX ID: $maxID - Max PRICE: $maxPrice";

Use the max() function to determine the highest number of a set.

3
  • If $id is an ARRAY, simply use echo max($id). If $id is a STRING, use echo max(explode(",", $id)) maybe...
    – Rob W
    Commented Jun 27, 2013 at 16:29
  • yeah but if i echo $maxPrice = max($price, $maxPrice); inside the loop it echos the 3 values // RESULTS: 180.00, 250.00, 300.00
    – Ered
    Commented Jun 27, 2013 at 16:31
  • You're in a loop... For each iteration of the loop, you're echoing the value. If it loops 10 times, you'll see 10 different outputs. My original answer will alleviate this (edited to remove the echo inside the loop).
    – Rob W
    Commented Jun 27, 2013 at 16:33
1

Either you use SQL's MAX() if you can modify your SQL query, or keep the max value in a variable in each loop, and reassign it everytime:

$firstLoop = true;
$maxId = 0;
$maxPrice = 0;

for ($i0 = 0; $i0 < $total0; $i0++)
{
    $id = $oconecta->retrieve_value($i0, "id_tam_product");
    $price = $oconecta->retrieve_value($i0, "price_tam_product");

    if ($firstLoop) {
        $firstLoop = false;
        $maxId = $id;
        $maxPrice = $price;
    }
    else {
        $maxId = max($maxId, $id);
        $maxPrice = max($maxPrice, $price);
    }
}

(the boolean is here if you have negative values it wouldn't work if $maxPrice and $maxId are initiliazed with 0)

2
  • when i echo $maxPrice = max($maxPrice, $price); the result is: 250.00, 300.00 i only need the highest value
    – Ered
    Commented Jun 27, 2013 at 16:28
  • You have to echo it AFTER the for loop.
    – roptch
    Commented Jun 27, 2013 at 16:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.