Doubt with loop of repetition

Asked

Viewed 110 times

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);

2 answers

4


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

<?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);

?>
  • 1

    It worked @Sergio, thank you very much. This Join I did not know, I will research more about

0

Another possible solution:

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

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

ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.