I'm starting to learn php today and I cannot figure out how to sum all 3 numbers by these loops [for, do, do while] loop. I can't even get passed through for loop.
Here is my current code :
<?php
$sum =0;
@$a= $_GET['a'];
@$b= $_GET['b'];
@$c= $_GET['c'];
for($i = $a; $i<=$c; $i )
{
$sum = $a ;
}
echo "Sum of $a , $b , $c is ".$sum;
?>
<body>
<form>
Enter first number <input type = "text" name="a"><br>
Enter second number <input type = "text" name="b"><br>
Enter third number <input type = "text" name="c"><br>
<input type = "submit" value="add">
</form>
</body>
CodePudding user response:
you can add them in an array and then add them in the loop.
<?php
$sum =0;
$a= $_GET['a'];
$b= $_GET['b'];
$c= $_GET['c'];
$arr = array($a,$b,$c);
for($i = 0; $i <= count($arr); $i )
{
$sum = $arr[$i];
}
echo "Sum of $a , $b , $c is ".$sum;
?>
CodePudding user response:
The setup you have isn't ideal for a loop as you would be manually creating an array, then looping which is backwards.
You could instead change your inputs so that you receive them as an array:
<?php
$sum = 0;
$values = $_GET['to_sum'];
for ($i = 0;$i <= count($values);$i ) {
$sum = $values[$i];
}
echo "Sum of " . join(", ", $values) . " is " . $sum;
?>
<body>
<form>
Enter first number <input type = "text" name="to_sum[]"><br>
Enter second number <input type = "text" name="to_sum[]"><br>
Enter third number <input type = "text" name="to_sum[]"><br>
<input type = "submit" value="add">
</form>
</body>
CodePudding user response:
You can go through the code given below using all the loops mentioned in your question. for your convenience I have suppressed all the errors using @ sign.
<?php
# setting variable a$ as array if not found in the get request
$_GET['a'] = isset($_GET['a']) && $_GET['a'] ? $_GET['a'] : [];
$forSum = 0; #inital the sum will be 0
#calculate sum for every element present in the array
for($i=0; $i < count($_GET['a']); $i ) {
@$forSum = $_GET['a'][$i];
}
#print sum
echo 'For loop sum : ' . $forSum;
$whileSum = 0;
$iterator = 0;
#calculate sum for every element present in the array
while($iterator < 3) {
@$whileSum = $_GET['a'][$iterator];
$iterator =1;
}
#print sum
echo '<br / >While loop sum : ' . $whileSum;
$doWhileSum = 0;
$iterator = 0;
#calculate sum for every element present in the array
do {
@$doWhileSum = $_GET['a'][$iterator];
$iterator =1;
} while($iterator < 3);
#print sum
echo '<br / >Do While loop sum : ' . $doWhileSum;
echo '<br /><br />';
?>
<html>
<head>
<title> Add With Loops </title>
</head>
<body>
<form>
First number <input type="text" name="a[]" value="<?php echo @$_GET['a'][0]; ?>"><br>
Second number <input type="text" name="a[]" value="<?php echo @$_GET['a'][1]; ?>"><br>
Third number <input type="text" name="a[]" value="<?php echo @$_GET['a'][2]; ?>"><br>
<input type="submit" value="Add">
</form>
</body>
</html>