For loop with a condition

O’, trying to create this SVG with PHP


Heres how I display the numbers (1-20)

<text text-anchor="middle" x="35" y="120">1</text>
<text text-anchor="middle" x="35" y="185">3</text>
<text text-anchor="middle" x="35" y="250">5</text>
<text text-anchor="middle" x="35" y="315">7</text>
<text text-anchor="middle" x="35" y="380">9</text>
<text text-anchor="middle" x="35" y="445">11</text>
<text text-anchor="middle" x="35" y="510">13</text>
<text text-anchor="middle" x="35" y="575">15</text>
<text text-anchor="middle" x="35" y="640">17</text>
<text text-anchor="middle" x="35" y="705">19</text>
....
..;. 
<text text-anchor="middle" x="487" y="120">2</text>
<text text-anchor="middle" x="487" y="185">4</text>
<text text-anchor="middle" x="487" y="250">6</text>
<text text-anchor="middle" x="487" y="315">8</text>
<text text-anchor="middle" x="487" y="380">10</text>
<text text-anchor="middle" x="487" y="445">12</text>
<text text-anchor="middle" x="487" y="510">14</text>
<text text-anchor="middle" x="487" y="575">16</text>
<text text-anchor="middle" x="487" y="640">18</text>
<text text-anchor="middle" x="487" y="705">20</text>

In order to do this with PHP, is this right?

for ($x = 1; $x < 20; $x++) {
   if($x % 2 == 1) {
  echo '<text text-anchor="middle" x="35" y="'.(120 + (($x - 1 ) * 32.5)).'">'.$x.'</text>';
	}  else {
	  echo '<text text-anchor="middle" x="487" y="'.(120 + (($x - 2 ) * 32.5)).'">'.$x.'</text>';
	}
echo "\r\n";
}

Does it work? Yes.

Could it be simplified? Yes.

Do you care?

Aside from not actually going to 20, does it produce the result you want?

If you apply Don’t Repeat Yourself (DRY) coding, and only write logic for things that change - you have a starting x and y value, that you are adding/resetting offsets to, to arrive at the coordinates. You can do it this way -

$x0 = 35; // start
$x1 = 452; // offset

$y0 = 120; // start
$y1 = 65; // offset

// initial values
$x = $x0;
$y = $y0;
foreach(range(1,20) as $n)
{
	echo "<text text-anchor='middle' x='$x' y='$y'>$n</text>\r\n";
	
	// next column
	$x += $x1;
	// end of row
	if($n % 2 == 0)
	{
		$x = $x0; // reset column
		$y += $y1; // next row
	}
}

For any given index $n;
$x = 35+(($n-1) % 2 * 452);
$y = 120+floor(($n-1) / 2)*65;

(This is also a good example of why 0-indexing is helpful for maths sometimes/often.)

1 Like

thanks, thats such a better way to think about it.