This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between if () { } and if () : endif;
Simple question,
When I started programming PHP I was shown my if statements like this:
If(1 == 1):
Echo 'hello world';
Endif;
Where as most people prefer
If(1== 1) {
Echo 'hello world';
}
Is there any difference? Does is improve the speed of the script or is it Better than the way I do it?
The statement are equals though for a better legibility in a Model View Controller project is better to use
if(1== 1) {
echo 'hello world';
}
in model/controller part and the other one in the View part.
<? if(1 == 1): ?>
<div>..</div>
<? endif;?>
so a web designer/ graphic can better handle html code.
No. However, you should not think about micro optimization (it's the root of all evil), especially since you name yourself a beginner.
The second one is more common, the first one is often more readable when mixing php and html.
There is no speed difference between them. This is an alternate syntax of if.
Some people prefer if() { or some prefer if ():
I personally use if (): when there is a bunch of HTML need to output.
<?php if (condition) : ?>
//some html tags html
<?php endif; ?>
and I use if(condition) { when some php processing to be done.
<?php
if (condition)
{
//other PHP stuff
}
?>
Personally I use alternative syntax when I mix PHP with HTML (its much cleaner this way for me):
<p>
<label>Customer:</label>
<?php echo Form::input('customer', Arr::get($post, 'customer'), array('maxlength' => 80)) ?>
<?php if (isset($errors['customer'])): ?>
<span class="error"><?php echo $errors['customer'] ?></span>
<?php endif ?>
</p>
Other then that there is no difference.
Is there any difference? Does is improve the speed of the script or is it Better than the way I do it?
No.
That's just two different ways to do the same thing.
For the second one almost every good code editor/IDE will highlight the matching brace.
Such a reason, along with the fact that curly braces are compatible with many other languages, makes them used more often.
Related
In Can HTML be embedded inside PHP "if" statement?, the accepted (and most upvoted) answer mentions only the alternative if style.
The other 2 answers mention it works with normal if, as well, but is it standards-compliant, or is it non-standard but supported behavior?
I mean this code:
<?php if ($cond) { ?>
If branch<br>
<?php } else { ?>
Else branch<br>
<?php }?>
Yes, the standard syntax in PHP works.
As suggested by the term standard I used in my last sentence, I really meant that it is the standard syntax. It always worked. It will always work.
Consider the alternative syntax alternative, that is, non-standard. The wording is from the PHP manual, not from me personally.
Alterantive already suggests that it works exactly the same, so you can use any of those, despite the votes on some Q&A platform somewhere in the world wide web :)
<?php if ($condition) { ?>
This will only display if $condition is true
<?php } ?>
By request, here's elseif and else (which you can also find in the docs: elseif; else)
<?php if ($condition) { ?>
This will only display if $condition is true
<?php } elseif($anotherCondition) { ?>
more html
<?php } else { ?>
even more html
<?php } ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
I hope this exemplary reqplique does add enough clarity if there were any doubts.
I can’t find answer anywhere or just don’t get it.
So, I have HTML and PHP code combined in my PHP file. In books it’s written that the code in <?php ?> are executed on server only and html will display in browser. But I don’t understand THIS:
<?php if ($a = $b) { ?>
<p>Text when condition is true</p>
<?php } else { ?>
<p>Text when condition is false</p>
<?php } ?>
The above is working in browser but I don’t understand why it doesn't output error
or at least it should output both sentences.
For me it seems that the statement is broken into peaces and the only way when it should work is:
<?php
if ($a = $b)
{
echo "<p>Text when condition is true</p>"
} else {
echo "<p>Text when condition is false</p>"
}
?>
What do I miss here?
It's just the way it works. PHP is a templating language and you can play tricks like that.
A piece of HTML in between two PHP blocks is interpreted as "output these characters".
It's generally a good idea to keep this kind of intermixing of PHP and HTML to a minimum, though - any serious back-end code that goes beyond simple if/else structures or loops should be in a separate location.
The former is useful when you need to output several html depending on the condition. Imagine you need to load a whole div with text. Doing with html is easier to handle. For small conditions like your example, the second example would make more sense.
Okay, so I have a question. I use print <<< END followed by an END; after my html and variables instead of echo and print. I use this because it doesn't seem to have an effect on speed and the code just looks more organized in my opinion. I'm sure others will disagree but it's just my opinion.
I have a current project and that's the primary method I use to output HTML. No problems so far.
What are the disadvantages to using this? I have spoken with coders about it before, but they never really give me a reason not to use it just to not use it. I would appreciate any advice on this because I haven't had any problems with it.
The syntax you're describing is called a heredoc. As far as I know there is no performance difference between using heredocs and single- / double-quoted strings.
Heredocs can often help to prevent syntax errors, because there is no need to escape ' and " within the string. Another option would be to jump out of PHP into plain HTML, which requires no echo calls whatsoever:
<?php
... do things ...
?>
<div id="result"><?php var_dump($result); ?></div>
<?php
... do more things ...
?>
The only disadvantage i can think of is its harder to read for developers. This too is opinion but i find it much easier to read alternate syntax in template files, i.e.:
<?php if($something): ?>
<div id="something">
<?php echo $something->text ?>
</div>
<?php endif; ?>
And switching in and out like this is the only reason i can see to use heredoc as far as html is concerned. IF you have functions that are outputting massive amounts of html then you should change those to include a file in some manner. IE. you shoudl need to switch in and out of html except in your view, and those views should be separate completely form your functions or models. for exampl you should be doing:
function getSomething($var){
if($var){
$html = <<< HTML
<div id="something">
$var->text
</div>
HTML;
}
}
This is obvioulsy a simle example and actually this example isnt so bad, but if the HTML is more complex it starts to get jsut ugly. And in the case of methods on model classes its just plain evil no matter how simple the HTML is. Id prefer something like the following:
getSomething($var, $template = 'something.php')
{
if($var){
ob_start();
include($template); // $var is accessible in something.php
return ob_get_clean();
}
return null;
}
Of course the include will result in slight a performance hit but thats where caching comes in :-)
Well the question is self explanatory.
In PHP when do I use the if/endif notation instead of the standard if(something){} notation?
Example:
<?php if($a == 5): ?>
A is equal to 5
<?php endif; ?>
Versus:
<?php if($a == 5){ ?>
A is equal to 5
<?php } ?>
Others have given the answer "for templating", but haven't really explained why. Curly braces are great for denoting blocks, but they kind of rely on indentation to be read clearly. So this is fairly clear:
<?php
if (1 == 2)
{
while (1 < 2)
{
doSomething();
}
}
It's obvious which brace matches which.
If, however, you're going into an HTML block, you're probably going to stop indenting cleanly. For instance:
<?php
if (1 != 2) { ?>
<div>This always happens! <?php while (true) { ?>
<p>This is going to cause an infinite loop!</p>
<?php }
}
That's hard to follow. If you use the endif style, it looks a little cleaner:
<?php
if (1 != 2): ?>
<div>This always happens! <?php while (true): ?>
<p>This is going to cause an infinite loop!</p>
<?php endwhile;
endif;
The content of the code shows more clearly what's being done. For this limited case, it's more legible.
Short answer:
Always use if($something) { } and pretty much never use if/endif. It's standard since PHP 4.0.0 and while the old syntax is not going away this is the one everybody expects.
If you are really looking for a case where you can use if/endif then it's when using php as a template language.
Some people like something like this:
<?php if ($foo): ?>
Hi There
<?php else: ?>
cya!
<?php endif; ?>
better than
<?php if ($foo) { ?>
Hi There
<?php } else { ?>
cya!
<?php } ?>
and imho it is because every line "speaks" and that can be helpful when there is a lot of html inbetween the php tags.
Both methods are acceptable. Some people maintain that the alternative syntax (endif) is more legible in templates. IMHO, with a modern syntax coloring/highlighting error, that no longer holds true. Just pick a style and stick with it.
It is a stylistic choice. They are analogous and one is not better than another.
The former can be good in certain circumstances because it may be easier to read when mired in the middle of an HTML block set.
I mostly use if/endif when stopping and starting the php code block in between, so nearly always when raw html is being outputted.
For example:
<?php if ($n == 3): ?>
Lorem ipsum.
<?php endif; ?>
This looks, at least in my opinion, better than the following:
<?php if ($n == 3) { ?>
Lorem ipsum.
<?php } ?>
You can use both, but preffered style and currently known style is the standard if(expr).
I asked another question about HTML and PHP separation as I have seen references to it on tutorial and examples pages but I found that separation of HTML and PHP it something different than what people are actually commenting on and I think that is PHP modes.
That is breaking out of PHP or not. Should It be done? Is it important?
Is it just a matter of preference to echo my HTML output or should I break out to display it?
Example:
<?php
echo '<html'>;
?>
vs.
<?php
dostuff();
?>
<html>
<?
morestuff();
?>
I assume by "breaking out" you mean:
<?php foo(); ?>
test
<?php bar(); ?>
as opposed to
<?php
foo();
echo("test");
bar();
?>
Well, one advantage of the first solution is that your layout is still more or less readable in HTML editors. Also, it separates layout and logic, at least more than the other variant. It is probably also slightly faster than the second option because no strings need to be parsed and echo'ed. On the flipside, having tons and tons of individual PHP-blocks can really be hard to read because things that are semantically related are suddenly split. You can, of course, also combine both approaches.
I think the bottom line here is that as soon as you need to do so much formatting and echo'ing that the logic of your program becomes really obscured, you should consider using a 'real' template engine.
I think it depends on the situation.
how many lines do you want to echo to the browser?
do the lines contain $variable values? $array values?
do you loop trough a dataset? etc etc.
To me, it is more reable to just echo the lines most of the time.
<?php
if ( check($something) ) {
echo "Some variable is: $something<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
can be more readable than:
<?php
if ( check($something) ) {
?>
Some variable is: <?php echo $something; ?><br/>
<?php
} else {
?>
Some variable is something else!<br/>
<?php
}
?>
and with some IDEs (or stackoverflow.com syntaxhighlighting for example), it can even be more readable to use:
<?php
if ( check($something) ) {
echo 'Some variable is: '.$something."<br/>\n";
} else {
echo "Some variable is something else!<br/>\n";
}
?>
In summary:
PHP offers you a lot of options to send content to your client.
The 'best method' differs from case tot case.
Choose the method that is most readable/maintainable and use it consistently.
If by breaking out you mean this sort of thing:
<?php
if($somecondition) {
?>
<!-- Some HTML -->
<?php
}
?>
Then yes, breaking out is better in most cases as it is more readable (many IDES highlight HTML syntax, and cannot do so if it is withing a string when being echo() ed)