Coding PHP Loops Easily post thumbnail

Coding PHP Loops Easily

Working with loops on PHP is inevitable, and I’ve seen many beginners (read: me) pulling their hair because of it. The thing with coding a loop is, sometimes you have to do stuffs like this:

<?php for ($i=1; $i < 10; $i++) { echo "<a href=\"something.php?id=$i\">No $i</a>"; }

Am I right am I right?

Looks complicated? Hell yeah. Truth is, there’s a much simpler way to achieve the same goal. I learned this trick from Wordpress’ Loop. Check this out.

Let’s take a look at this piece of code, in here we’re doing a For loop:

<ul>
<?php
for ($i=1; $i<10; $i++) {
    echo "<li><a href=\"?p=$i\">Go to page # $i</a></li>";
}
?>
</ul>

As simple as that looks, the echo command could be a little tricky because we often have to use double quote and single quote characters inside. Debugging can be a pain in the ass.

An approach I propose: the Wordpress way. Here’s how:

<ul>
<?php
for ($i=1; $i<10; $i++) { ?>
    <li><a href="?p=<?php echo $i;?>">Go to page # <?php echo $i;?> </a></li>
<?php }
?>
</ul>

This way we exclude the HTML tags from the PHP loop. Wow I can’t really describe that, if you do PHP you know what I mean. Now you can HTML not inside the echo command.

Wordpress is using this approach on templating and I find it very easy to use once you get used to it. So why don’t you give it a try and let us know what you think :)

[Post to Twitter] Tweet This  [Post to Delicious] Delicious This  [Post to Digg] Digg This  [Post to Ping.fm] Ping This  [Post to Reddit] Reddit This  [Post to StumbleUpon] Stumble This 

4 Comments

  1. My own preference in this case would be…
    <?php
    $output = array();
    for ($i = 1; $i < 10; $i++) {
    $output[] = 'Go to page # ' . $i . '';
    }
    print implode("\n", $output);
    ?>

    or if wrapped in a function (as it probably should be), this would return $output, not print it.

    (you should have a preview option, btw)

  2. oh well.

  3. To make it more simple, if you want just to echo the value, instead using
    try using

  4. *woops, got cleanup*
    To make it more simple, if you want just to echo the value, instead using
    try using

Leave a Reply

(required)

(will not be published) (required)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>