Reputation:
I need to subtract 10 from a value until it's below ten and then use it outside of the loop but the value doesn't seem to change. I'm not sure how many wrongs I'm making but I bet it's many!
$x = 1987;
$y = 2015;
$b = $y - $x;
for($b; $b > 10; $b - 10){
echo $b; //This is supposed to be echo:ed when the loop is done
}
Thanks in advance!
Upvotes: 0
Views: 65
Reputation: 1057
A while loop is more readable than a for loop. Also, put the echo statement after the loop has completed.
$x = 1987;
$y = 2015;
$b = $y - $x;
while($b > 10) {
$b -= 10;
}
echo $b;
Upvotes: 0
Reputation: 811
Or you could just do
$x = 1987;
$y = 2015;
$b = ($y - $x) % 10;
Which is basically what you're doing, only you chose the hard way with the for
loop :)
Upvotes: 1
Reputation: 1416
$x = 1987;
$y = 2015;
$b = $y - $x;
for(; $b > 10; $b -= 10);
echo $b;
echo will happen only after completing loop. This will reduce the $b
value by multiples of 10. $b
will be less than 10
after loop.
Upvotes: 0
Reputation: 56
$x = 1987;
$y = 2015;
$b = $y - $x;
for($b; $b > 10; $b -= 10) {
echo $b;
}
Upvotes: 0
Reputation: 2426
You are not actually modifying $b
:
$x = 1987;
$y = 2015;
$b = $y - $x;
for($b; $b > 10; $b = $b - 10) { // <- this line
echo $b;
}
Also, there is no need for the initial $b
here:
for(; $b > 10; $b = $b - 10) {
Or you could get rid of:
$b = $y - $x;
And just use:
for($b = $y - $x; $b > 10; $b = $b - 10) {
Upvotes: 2