Close code blocks in PHP sections?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gordonwd
Forum Newbie
Posts: 3
Joined: Fri Mar 06, 2009 9:04 am

Close code blocks in PHP sections?

Post by gordonwd »

Within each section of PHP in a given page -- that is, between the <?php and ?> -- is it necessary to close all PHP control structures? In other words, can you have an if, foreach, etc. with an opening brace, end that PHP block with ?>, then further down the page start another <?php block and have the closing brace in that block?

If so, it seems a bit weird to me (and confusing) to program that way. Any HTML intervening between the PHP sections could of course not have any variable substitution, but I suppose there could be cases where this would be useful. If I have chunks of HTML to put out within a control structure, I usually use a print with HEREDOC syntax.

Another point of confusion is that if the interrupted control structure is an "if", the HTML would be emitted regardless of the conditional situation, e.g.:

<?php>
if (false) {
?>
<p>This is output regardless of the if condition</p>
<?php
// other code
}
?>

Am I correct in all of this?

Doug G
User avatar
susrisha
Forum Contributor
Posts: 439
Joined: Thu Aug 07, 2008 11:43 pm
Location: Hyderabad India

Re: Close code blocks in PHP sections?

Post by susrisha »

yes thats possible

Code: Select all

 
<?php
$somevar =true;
if($somvar==true)
{
?>
Somevar is true
<?php
}
else
{
?>
Somevar is not true
<?php
}
?>
 
The above code prints Somevar is true. Try to copy the same into a html page and see how it goes by changing the value..
Infact i have written codes which execute totally differently depending on the variables got and if conditions...
gordonwd
Forum Newbie
Posts: 3
Joined: Fri Mar 06, 2009 9:04 am

Re: Close code blocks in PHP sections?

Post by gordonwd »

Thanks for clearing that up. I thought that the HTML would be processed regardless of the conditional, and not treated as part of the conditional block. From your example, that's not true, which actually makes it work more logically.
Post Reply