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 
Baba
  • 94,024
  • 28
  • 166
  • 217
Ered
  • 465
  • 1
  • 6
  • 23

2 Answers2

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.

Rob W
  • 9,134
  • 1
  • 30
  • 50
  • If $id is an ARRAY, simply use `echo max($id)`. If `$id` is a STRING, use `echo max(explode(",", $id))` maybe... – Rob W Jun 27 '13 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 Jun 27 '13 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 Jun 27 '13 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)

roptch
  • 225
  • 1
  • 6