Search code examples
phpforeachforeach-loop-container

using foreach loop how to add sum of vlue in using php


how to add each increment value using foreach loop my out put should be like

   1
   1+2 = 3
   1+2+3 = 5

my code fallows as

   <?php
    $value = array('1',2',3);
    foreach ($value as $prin) 
    {
    echo prin;
    }
    ?>

is it true to write ??


Solution

  • Well you're looking for this:

    <?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
    }