Add Array from multiple fields

4

I have a form with several fields containing currency values 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

    
asked by anonymous 20.10.2015 / 17:20

3 answers

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 from array_sum;

    
20.10.2015 / 18:06
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
    
20.10.2015 / 17:54
4

Resolution:

$length_array = count($_POST['valor']);
$soma = 0;

for ($i = 0; $i < $length_array; $i++){
    $soma = $soma + $_POST['valor'][$i];
}

echo 'A soma é: '.$soma;

Or inside the loop for ():

$soma += $_POST['valor'][$i];

References:

link

link

    
20.10.2015 / 17:47