Ahmad Khan
Ahmad Khan

Reputation: 529

How can I do addition repetition in PHP

For example, I have a small function that I want it to keep adding to it its results .

$test1 = 1;
$test2 = 2;
$doitanumbeoftime = 6;

$results = $test1 + $test2;

echo $results; //// which it will print out 3.

now my question, after the $results was found, I want that results to be added to $test2 variable and find that results and add it to $test2 one more time and so on till it did it 6 times.

So, I need a function/ loop that can illustrate this results.

so for the first results, it should be 3. second results should be 5. 3rd results should be 7 4th results should be 9 5th results should be 11 and the 6th results should be 13.

Upvotes: 2

Views: 131

Answers (4)

Serge Bekenkamp
Serge Bekenkamp

Reputation: 426

I think this is what you are looking for.

for ($i = 0; $i < $doitnumberoftimes; $i++) {
    $results = $test1 + $test2;
    $test2 += results;
    echo $results;
}

Upvotes: 1

vdbuilder
vdbuilder

Reputation: 12964

this creates the output you ask for (3, 5, 7, 9, 11, 13):

$test1 = 1;
$test2 = 2;
$doitanumbeoftime = 6;

$result = $test1;
for ($i=0;$i<$doitanumbeoftime;$i++){
    $result = $result + $test2;
    echo $result . "<br />";
}

Upvotes: 0

Ayush Pateria
Ayush Pateria

Reputation: 630

$test1 = 1;
$test2 = 2;
$doitanumbeoftime = 6;

$results = $test1 + $test2;

for($i = 1; $i < $doitanumbeoftime; $i++)
$results += $test2;

echo $results;  // 13

Upvotes: 0

Ry-
Ry-

Reputation: 224904

Like this?

$test1 = 1;
$test2 = 2;
$times = 6;

for($i = 1; $i <= $times; $i++) {
    echo $test1 + $test2 * $i . '<br />';
}

Upvotes: 4

Related Questions