Breaking News

# For loop with condition – PHP – SitePoint Forums

O’, trying to create this SVG with PHP

This is how I display the numbers (1-20)

``````1
3
5
7
9
11
13
15
17
19
....
..;.
2
4
6
8
10
12
14
16
18
20
``````

To do this with PHP, is that correct?

``````for (\$x = 1; \$x < 20; \$x++) {
if(\$x % 2 == 1) {
echo ''.\$x.'';
}  else {
echo ''.\$x.'';
}
echo "rn";
}
``````

Does it work? Yes.

Could it be simplified? Yes.

Are you interested?

Besides not going to 20, does this produce the result you want?

If you apply Do Not Repeat (DRY) coding and only write logic for things that change – you have a starting x and y value, to which you add/reset offsets, 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 "\$nrn";

// 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 indexing to 0 is sometimes/often useful for math.)

1 like

thanks, that’s a better way to think about it. 