Search code examples
phparrayssummultiplication

PHP calculating two arrays and then add their sum


I want to calculate an array to another array and then add both like this :

   Array1(4,8,7,12);
   Array2(3,6);
   

the result is like this : 3x4+3x8+3x7+3x12+6x4+6x8+6x7+6x12 = 279

I tried with this code and since I'm still new with php I still didn't make any tips I'll be glad thanks in advance

<?php 



tab1(4,8,7,12);
tab2(3,6);
$s=0;
for($i=0; $i<$tab1[3]; $i++){
       for($j=0; $j<$tab2[1]; $j++){
           $s = $s + tab[i] * tab[j];
}
echo "$s";
}
?>


Solution

  • This is actually a piece of cake. I am not sure what tab1 means but I assume you are trying to use this function to get an array of desired(input) numbers.

    Using a foreach loop to loop over the two arrays, I came up with the code below:

    <?php
    $a = [4,8,7,12];
    $b = [3,6];
    $sum = 0;
    foreach ($b as $valueInB) {
        foreach ($a as $valueInA) {
            $sum += $valueInA * $valueInB;
        }
    }
    echo $sum;
    ?>
    

    which results in:

    279
    

    if you are insisting on using a for loop you can run the code below to get the same result:

    <?php
    $a = [4,8,7,12];
    $b = [3,6];
    $sum = 0;
    $bLength = count($b);
    $aLength = count($a);
    for ($i=0; $i < $bLength  ; $i++) { 
        $valueInB = $b[$i];
        for ($j=0; $j < $aLength ; $j++) { 
            $valueInA = $a[$j];
            $sum += $valueInA * $valueInB;
        }
    } 
    echo $sum;
    ?>
    

    Please note that you should use the count outside of the loop because looping over the array and calling count each time is not an efficient way. (Thanks to Will B for the comment)