Nick
Nick

Reputation: 639

Php variables not adding together

The code is pretty straight forward, however it is just not running the way it is expected to, basically the numbers get added at the end in order to continue the while loop. But they are just not adding, the $two and $i that is

PHP:

$i=1;
$two=2;
$add=9;
$count=1;
while($i<=7488){
    echo $count;
    echo $exploded[$two];
    echo "<br>count=".$count."<br>";
    echo "<br>two=".$two."<br>";
    echo "<br>i=".$i."<br>";
    $count++;
    $two+$add;
    $i+$add;
}

Upvotes: 0

Views: 2090

Answers (6)

Will Vousden
Will Vousden

Reputation: 33358

How about this:

$two += $add;
$i += $add;

$two + $add is just an expression that returns the sum of the two variables; it doesn't actually do anything or change any state.

$two += $add (+= is the addition assignment operator) is equivalent to $two = $two + $add. Analogous operators exist for other arithmetic operations (e.g. *=, -=, etc.).

This pattern is true for all C-like languages (to my knowledge), and many other languages too.

Upvotes: 7

Desty
Desty

Reputation: 2776

The term

$i+$add;

produces a result, but you throw that result away. If you would to save the result in $i again, you should try

$i = $i + $add;

or

$i += $add;

(Both statements do the same, the latter is just a shortcut.) The same holds for the other variables.

Upvotes: 0

Marc B
Marc B

Reputation: 360702

You're not saving your addition anywherE:

$two+$add;
$i+$add;

so the result of addition is simply tossed away.

Try:

$two = $two + $add;
or
$two += $add;

Upvotes: 2

Bogdan Burym
Bogdan Burym

Reputation: 5512

You do not modify this variables:

$two+$add;
$i+$add;

Maybe you need:

$two+=$add;
$i+=$add;

Upvotes: 2

Ricardo Lohmann
Ricardo Lohmann

Reputation: 26320

You have to assign $two+$add;, $i+$add; to some var.

Upvotes: 2

David Harris
David Harris

Reputation: 2707

It doesn't work like that. $two+$add has a return value. You need to assign it to something.

Upvotes: 3

Related Questions