-3

I have a simple form and a submit button. After pressing the submit button, get the values (they will be numbers) and calculate the sum. And again calculate the sum of individual digits stored in sum.

A better explanation: 1+2+3+4=10 where 1,2,3 and 4 are user inputs from the form. And the sum 10 has to be split-ted and summed again as 1+0=1. And this would be my final result. So far I did the task where it gives me the first sum. I don't know what to do to display the second result which I want to be the finale.

<?php 
$a='';
$sum='';
$total='';
if (!isset($_POST['submit'])) {

echo " ";
}
  else  {
        $a = array($_POST['textfield'],$_POST['textfield1'],$_POST['textfield2'],$_POST['textfield3'],$_POST['textfield4'],$_POST['textfield5'],$_POST['textfield6'],$_POST['textfield7'],$_POST['textfield8'],$_POST['textfield9'],$_POST['textfield10'],$_POST['textfield11'],);
                for ($i=0; $i<=12; $i++) {

        $sum= array_sum($a);

        $total= ;

        }


  }



         echo "sbora e: $total "; 
?>
halfer
  • 19,824
  • 17
  • 99
  • 186
user3194814
  • 1
  • 1
  • 3

2 Answers2

1

So you want to build the cross sum of your first result:

$result2 = 0;
//cast integer to string
$strTotal = (string) $total;
//loop over "chars" and add them to your second result
for($i=0; $i < strlen($strTotal); $i++)
{
    $result2 += $strTotal{$i};
}
Tobias Golbs
  • 4,586
  • 3
  • 28
  • 49
1
$total = array_sum(str_split($sum));

Using Artefacto's method.


On another note,

$a = array($_POST['textfield'],$_POST['textfield1'],$_POST['textfield2'],$_POST['textfield3'],$_POST['textfield4'],$_POST['textfield5'],$_POST['textfield6'],$_POST['textfield7'],$_POST['textfield8'],$_POST['textfield9'],$_POST['textfield10'],$_POST['textfield11'],);

can be written as,

$a = array();
for ($i = 0; $i <= 11; $i++){
     if (isset($_POST["textfield_$i"]))
     array_push($a, $_POST["textfield_$i"]);
}

if the names of the fields are:

textfield_0, textfield_1, textfield_2...
Community
  • 1
  • 1
Eisa Adil
  • 1,743
  • 11
  • 16