如何使用 foreach 循环添加每个增量值我的输出应该像
1
1+2 = 3
1+2+3 = 5
我的代码休闲为
<?php
$value = array('1',2',3);
foreach ($value as $prin)
{
echo prin;
}
?>
写的是真的吗??
如何使用 foreach 循环添加每个增量值我的输出应该像
1
1+2 = 3
1+2+3 = 5
我的代码休闲为
<?php
$value = array('1',2',3);
foreach ($value as $prin)
{
echo prin;
}
?>
写的是真的吗??
那么你正在寻找这个:
<?php
$values = array(1,2,3);
$values_count = count($values);
for ($i=0; $i < $values_count; $i++) { // loop $values_count number of times
$str = ''; // this string will store the part before = in each line
$total = 0; // initialize total to 0 after printing every line
for ($j = 0; $j <= $i; $j++) { // loop across the first $i values in the $values array
$str .= $values[$j] . " + "; // append to the string
$total += $values[$j]; // add to total
}
$str = substr($str, 0, -3); // remove the final ' + ' from the string
echo $str . ' = ' . $total . "\n\n"; // print line
}
很久没用php了
<?php
foreach($value as $prin)
{
$res = 0;
for($i = 1; $i <= $prin; i++)
{
$res = $res + i;
echo $i;
if($i != $prin) echo "+"
}
echo "=" + res;
}
?>
我认为您正在寻找这样的东西:
<?php
$value = array(1,2,3);
$sum = 0;
foreach ($value as $prin)
$sum += $prin;
echo $sum;
?>
一个简单的解决方案是:
<?php
$output = "";
$total = 0;
$values = array(1,2,3);
foreach ($values as $val)
{
$total += $val;
$output += $val . " + ";
echo $output . " = " . $total;
}
?>