Add Array from multiple fields

Asked

Viewed 463 times

4

I have a form with several fields containing values in currency as I can add all these values in the post output

Example form

<form id="form2" name="form2" action="includes/acao.php?form=faturamento"   
method="post" >
<input type='hidden' name='valor[{$id_finan}]'  value='{960.00}' />
<input type='hidden' name='valor[{$id_finan}]'  value='{960.00}' />
<input type='hidden' name='valor[{$id_finan}]'  value='{960.00}' />
</form

acao.php

foreach($_POST["checkbox"] as $key=>$value){    
echo $valor = mysql_real_escape_string($_POST['valor'][$key]);
// Retorno 960.00960.00960.00
}

How to bring this return already added

  • You want to add up before you get to the server, is that it? At the event submit form you can do this.

  • I prefer the sum to be made in the action.php

3 answers

5

# SIMULACAO
$post = array(
    'valor' => array(
        0 => 10,
        1 => 10,
        3 => 10,
        4 => 10,
        5 => 10,
        6 => 10,
        7 => 10,
    )
);

# RESOLUCAO
echo array_sum($post['valor']); // 70
  • I didn’t know this other way to add numerical type elements inside an array. + 1

4

3


Just to complement with another alternative, this time using foreach:

$post = array(
    'valor' => array(
        0 => 10,
        1 => 10,
        3 => 10,
    )
);  
$soma = 0;
foreach ($post['valor'] as $key => $value) {
    $soma += $value;
}

echo $soma //30

I would go array_sum;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.