我今天开始学习php,我不知道如何通过这些循环将所有3个数字相加,以便,做,做,同时循环。我甚至不能通过循环。
以下是我的当前代码:
<?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>发布于 2022-03-15 07:00:16
您所拥有的设置对于循环并不理想,因为您将手动创建一个数组,然后向后循环。
相反,您可以更改输入,以便将它们作为数组接收:
<?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>发布于 2022-03-15 06:48:21
您可以将它们添加到数组中,然后将它们添加到循环中。
<?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;
?>发布于 2022-03-15 08:52:29
您可以使用问题中提到的所有循环来查看下面给出的代码。为了您的方便,我用@符号消除了所有的错误。
<?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>https://stackoverflow.com/questions/71477467
复制相似问题