2
I am doing a series of exercises in PHP for practice. And I came across a question regarding the loop of repetition. To explain better I will put the statement of the exercise 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 the exercise the first factor passed is the number of times that factor 2 will have to be added up. By what the exercise asks I was able to accomplish the sum, but I also wanted to show the added values on the screen, for example, 5+5+5+5 = 20.
For this exercise I used array. Follow 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 this is if I pass factor 1 to number 4 and factor 2 to 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 the foreach the way it’s commented on above it prints an extra "+" sign, it’s 5 + 5 + 5 + 5 + 20.
Would anyone know of any solution to this case?
Grateful!
Try this: foreach ($arr as $key => $value) { $value .= $value . ' + '; } echo substr($value, 0, -1);
– Vítor André