I'm doing a series of exercises in PHP for practice. And I came across a question regarding loop repetition. To explain it better I'll put the exercise statement here:
Efetue um algorítmo PHP que receba dois valores quaisquer e efetue sua multiplicação utilizando para isso apenas o operador “+”, visto que:
(3 * 5) = 5 + 5 + 5
(4 * 12) = 12 + 12 + 12 + 12
In exercise the first factor passed is the number of times that factor 2 will have to be added. For what the exercise asks I was able to perform the sum, but I also wanted to show the values added on the screen, for example, 5 + 5 + 5 + 5 = 20.
For this exercise I used array. Here is my code:
<?php
$fator1 = isset($_POST['fator1']) ? $_POST['fator1']: '';
$fator2 = isset($_POST['fator2']) ? $_POST['fator2']: '';
for ($i = 1; $i <= $fator1; $i++) {
$arr[] = $fator2;
}
/*
foreach ($arr as $key => $value) {
echo $value . ' + ';
}
*/
echo array_sum($arr);
The way it is if I pass as factor 1 the number 4 and as factor 2 the number 5 it actually prints 20 on the screen. But what I want to print on the screen is 5 + 5 + 5 + 5 = 20.
But if I use foreach the way it's commented on above it prints a plus sign, it gets 5 + 5 + 5 + 5 + 20.
Would anyone know of any solution to this case?
Thank you!