Higher value in an array in PHP

4

I have a problem finding the largest value of the product box width for the freight of a website I'm making.

I put the product data with the size of the boxes in the database and I am now doing the calculations. I needed to add the weight and heights as the client requested and now I need to get the largest length and width of a set of products, but I can not do that ...

If anyone could help it would be great, follow the code below:

$total = 0;
            $alturaTotal = 0;
            $pesoTotal = 0;
            $larguraTotal = 0;
            foreach($_SESSION['carrinho'] as $id => $quantidade)
            {
                $sql = "SELECT * FROM produtos WHERE id = '$id'";
                $query = mysql_query($sql);

                while($row = mysql_fetch_assoc($query)) 
                {
                    $produto = $row['nome'];
                    $preco = $row['preco'];
                    $id = $row['id'];
                    $altura = $row['altura'];
                    $largura = $row['largura'];
                    $comprimento = $row['comprimento'];
                    $peso = $row['peso'];
                    $cepOrigem = $row['cepOrigem'];

                    $sub = $preco * $quantidade;
                    $total = $total + $sub;

                    $alturaTotal = $alturaTotal + $altura;
                    $pesoTotal = $pesoTotal + $peso;

                    foreach($_SESSION['carrinho'] as $id => $largura)
                    {
                        $larguraTotal = $largura;   
                    }
    
asked by anonymous 09.07.2015 / 21:06

1 answer

5

The logic is very simple, just use two variables and check if the width / length value is greater than what is in the variable, if it stores the new width / length value in it. Example:

// Declara as variáveis fora do loop
$maiorlargura = 0;
$maiorcomprim = 0;

// Atualiza o valor da variável dentro do loop
if ($maiorlargura < $largura = $row['largura'])
   $maiorlargura = $largura = $row['largura'];

if ($maiorcomprim < $comprimento = $row['comprimento'])
   $maiorcomprim = $row['comprimento'];

When the loop finishes, there will be the largest value in the variable. You can still get the product ID by updating a variable for this along with width / length.

    
09.07.2015 / 21:16