简体   繁体   中英

How to get max value in loop

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 
$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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM