Simple for loop

Greetings!
I believe it is so simple as ABC. But this thing here is frustrating me…


for($i = 1 ; $i <= $cp; $i++)
	{
		if ($i >= 0)
		{
		echo "<tr><td>";
		echo $i;
		echo "</td><td>";
		echo $p = $acc + $i;
		echo "</td></tr>";
		}
	}

My desired output is …
When I input $cp = 5, $i will count from 1 to 5
When I input $acc = 3, $p will count 3, 4, 5 ,6, 7.

In my code

When I input $acc = 3, the output of $p is 4, 5 ,6, 7, 8

Any help wil do.

Hi claro,

This does what you want:


$cp = null;
$cp = 5;
$acc = null;
$acc = 3;
echo '<table>';
for($i = 1; $i <= $cp; $i++){
   echo "<tr><td>"; 
   echo $i;
   echo "</td><td>"; 
   $p = ($acc - 1) + $i;
   echo $p;
   echo "</td></tr>";; 
}
echo '</table>';

Outputs

<table>
<tr>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
</tr>
<tr>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>6</td>
</tr>
<tr>
<td>5</td>
<td>7</td>
</tr>
</table>

You needed to use the brackets () around $acc -1 like show to have this evaluate prior to 1 being added; math in brackets always is given presidence over non bracketed parts of an equation. Of course the regular presidence of math also occurs in the multiplication is done prior to division which is done prior to addition which is done prior to subtraction.

You don’t need the if($i >= 0) as in your for loop you always set it to 1;

Steve

Of course the regular presidence of math also occurs in the multiplication is done prior to division which is done prior to addition which is done prior to subtraction.

I did not understand the explanation, but you’ve got what I want . Thank you very much sir steve! I’ll just do more experiment to understand this code. Thank you!

Hi claro,

Green = first
Blue = second
Red = third
Purple = fourth

This

[B][COLOR=#0000ff]10+[/COLOR][COLOR=#008000]5÷5[/COLOR] = 11[/B]

This code is actually evaluating like

[B]10 + (5÷5) = 10 + 1 = 11[/B]

This

[B][COLOR=#008000](10 + 5)[/COLOR][COLOR=#0000ff]÷5[/COLOR] = 3[/B]

This code evaluates like

[B](10 + 5) = 15 = 15÷5 = 3[/B]

This

[B][COLOR=#800080]10-[/COLOR][COLOR=#008000]5×10[/COLOR][COLOR=#ff0000]+[/COLOR][COLOR=#0000ff]5÷10[/COLOR] = -39.5[/B] 

Why? because × before ÷ before + before -. So this is getting grouped like

[B][COLOR=#800080]10&#8722;[/COLOR][COLOR=#008000](5×10)[/COLOR][COLOR=#ff0000]+[/COLOR][COLOR=#0000ff](5÷10)[/COLOR] = -39.5 [/B]

if we group it like

[COLOR=#008000][B](10&#8722;5)×(10+5)[/B][/COLOR][B][COLOR=#0000ff]÷10[/COLOR] = 7.5[/B]

The curved brackets cause whatever is inside the bracket to get processed before the other parts of the equation.

Hopefully this is a better explanations.

Regards,
Steve