Doubt with repeat loop

2

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!

    
asked by anonymous 22.05.2017 / 20:14

2 answers

4

This is a case of "trailing ..." , you can use a function to join array elements with the signal you choose. join or the implode do this:

<?php

$fator1 = isset($_POST['fator1']) ? $_POST['fator1']: '';
$fator2 = isset($_POST['fator2']) ? $_POST['fator2']: '';

for ($i = 1; $i <= $fator1; $i++) {
    $arr[] = $fator2;
}

echo join(' + ', $arr); 

echo array_sum($arr);

?>
    
22.05.2017 / 20:19
0

Another possible solution:

<?php
$num1 = 5;
$num2 = 4;

for($num2; $num2 > 0; $num2--){
    echo $num1;
    if($num2 != 1) echo " + ";
}

ideone

    
22.05.2017 / 20:23