I am kind of confused about how the below code works. In my head I am imagining each php block being executed as a whole and rendered to HTML. The fact that the first block is kind of incomplete with a hanging brace doesn't play nicely with how I imagine PHP to work. What does the PHP module do when it gets to a PHP closing tag? How is it that code inside the PHP tags can effect the output of plaintext outside of the PHP tags, i.e. only conditionally outputting the form?

I would have thought that to accomplish the below you would have actually had to use an echo statement to conditionally echo the form.

<html>
<head></head>
<body>

<?php
/* if the "submit" variable does not exist, the form has not been submitted - display initial page */
if (!isset($_POST['submit'])) {
?>

    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Enter your age: <input name="age" size="2">
    <input type="submit" name="submit" value="Go">
    </form>

<?php
    }
else {
/* if the "submit" variable exists, the form has been submitted - look for and process form data */
    // display result
    $age = $_POST['age'];
    if ($age >= 21) {
        echo 'Come on in, we have alcohol and music awaiting you!';
        }
    else {
        echo 'You're too young for this club, come back when you're a little older';
    }
}
?>

</body>
</html>

Accepted Answer

The PHP manual explains it pretty decently:

...when PHP hits the ?> closing tags, it simply starts outputting whatever it finds (except for an immediately following newline - see instruction separation ) until it hits another opening tag ... but for outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo() or print()...

Written by Rob Hruska
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the stackoverflow.com community.
It is licensed under cc-wiki