0

I've just recently started using PHP 5.4 and have noticed as of 5.3 you can use goto to jump to sections of code which I am using to jump from a loop section. My question is after having read this post... Is GOTO in PHP evil? is this bad practice in this case or is it a viable solution?

<?php
while ($thisResult = mysql_fetch_array($result)) {      
    if($article && $i > 0) {
        goto comments;
    }

?>
    <h2>
        <a href="/plugins/<?=$thisResult['post_name']?>"><?=$thisResult['post_title']?></a>
        <span><?=$thisResult['post_modified_gmt']?></span>
    </h2>
    <p class="content">
        <?=nl2br($thisResult['post_content']);?>
    </p>
    <br />  
 <?php
    comments: 
        if ($article) {
?>
        <p class="comment"><?=$thisResult['comment_content']?>
<?php
        }

    $i++;
}

 ?>
Community
  • 1
  • 1
KryptoniteDove
  • 1,278
  • 2
  • 16
  • 31

2 Answers2

1

This is called spaghetti programming and is a bad practice. http://en.wikipedia.org/wiki/Spaghetti_code

here is what you can do instead for your code

    <?php
    while ($thisResult = mysql_fetch_array($result)) {      
        if($article && $i > 0) {

        }
    else {
    ?>
        <h2>
            <a href="/plugins/<?php $thisResult['post_name']?>"><?php $thisResult['post_title']?></a>
            <span><?php $thisResult['post_modified_gmt']?></span>
        </h2>
        <p class="content">
            <?php nl2br($thisResult['post_content']);?>
        </p>
        <br />  
     <?php
    }
            if ($article) {
    ?>
            <p class="comment"><?php $thisResult['comment_content']?>
    <?php
            }

        $i++;
    }

     ?>

A simple else solves it. you can probably find more elegant solutions using switch cases or flags.

The problem is that your code will be hard to edit and add stuff to it.

Max Doumit
  • 1,065
  • 12
  • 33
1

This is rewrite of the same code without using goto, to show you that you can always make it without it

<?php
    while ($thisResult = mysql_fetch_array($result)):
        if(!$article || $i <= 0): ?>
            <h2>
                <a href="/plugins/<?php echo $thisResult['post_name']; ?>"><?php echo $thisResult['post_title']; ?></a>
                <span><?php echo $thisResult['post_modified_gmt']; ?></span>
            </h2>
            <p class="content">
                <?php echo nl2br($thisResult['post_content']); ?>
            </p>
            <br />
        <?php endif; ?>
        <?php if ($article): ?>
            <p class="comment"><?php echo $thisResult['comment_content']; ?></p>
        <?php endif;
        $i++;
    endwhile;

I used alternative syntax for control structures, and replaced <?= with <?php echo as it's much more readable to me. Also, other commenters gave you some good suggestions regarding separation of markup and db functions etc, so please give it a thought

Marko D
  • 7,576
  • 2
  • 26
  • 38