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
Close code blocks in PHP sections?
Moderator: General Moderators
Re: Close code blocks in PHP sections?
yes thats possible
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...
Code: Select all
<?php
$somevar =true;
if($somvar==true)
{
?>
Somevar is true
<?php
}
else
{
?>
Somevar is not true
<?php
}
?>
Infact i have written codes which execute totally differently depending on the variables got and if conditions...
Re: Close code blocks in PHP sections?
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.