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).
Related
I was surprised to find that you can break out of a PHP function into raw HTML and back. I knew that you could do this sort of thing with loops and conditionals, but this was a surprise to me. Is it an accident or is this well-defined behavior? (I couldn't find any explicit discussion of the function case in the manual.)
[NOTE: The following code doesn't give a good example of when I would use this behavior, but I kept it simple for demonstration purposes.]
<?php
$i = 0;
while($i++ < 3) {
?><p>I am in a while loop.</p><?php
}
// this part surprised me
function actSkeptical($adjective) {
?><p>Is it <?= $adjective ?> that this works?.</p><?php
}
actSkeptical("weird");
?>
Output:
I am in a while loop.
I am in a while loop.
I am in a while loop.
Is it weird that this works?
I know some people absolutely hate mixing PHP and HTML like this, but I can't do OOP/templating (for reasons I won't go into here) and I do like seeing as much raw HTML as possible.
Also, I don't quite understand the semantics of how the short open/close tag above (outputting $adjective) works in conjunction with the surrounding code. Does PHP just treat raw HTML like it was an echo statement? And then the <?= $adjective ?> is just like including a variable within a string?
I can't seem to find any documentation relating to the exiting of PHP tags within blocks. However, there's really only a few places escaping to HTML will work.
Normal Usage
<?php
php_related_code();
?>
//html/css/js/etc
Within blocks, such as while, for, functions, etc
<?php
for ($i = 0; $i < 5; $i++) {
?>
hello world
<?php
}
$i = 5;
while ($i-- > 0) {
?> hello there <?php
}
function myFunc() {
?>
hello universe
<?php
}
myFunc();
You can think of ?>stuff<?php similar to an echo or print command found in PHP, because you can escape to HTML in the same places you can echo. So you can echo within the main script, in for loops, and you can echo in functions. But you can't echo in an array, for example:
<?php
$array = array(echo "here"); //not allowed
$array = array(?>here<?php); //also not allowed
So you can think of escaping the same as echoing in which it can tell you where you can use it, but you can't do the same thing when you're thinking about what it does.
They act differently and are processed by PHP differently as well. But your question is only asking about any restrictions so I won't go into what are the differences between ?><?php and echo.
I forgot to mention, <?=$variable?> is just short tag for <?php echo $variable; ?> if you have this feature enabled.
This is called a spaghetti code. DO NOT USE IT.
If you really want to separate code, logic and markup start using MVC; YII is great.
http://www.yiiframework.com/
Also check this out: https://www.youtube.com/watch?v=mhwfFgSzg7U
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.
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.
I make this PHP script, but Dreamweaver points (as parsing of the code written) that this string is Incorrect.
In any case it works perfectly, but maybe I'm wrong somethings :
for($i=1; $i<=$npagine; $i++) {
?> <a <? if($i==$index) { ?> class="paginas" <? } else { ?> class="pagine" <? } ?> href="index.php?<?=$splitter_zone?>&index=<?=$i?>"><?=$i?></a> <?
}
Any ideas?
The code looks okay. However, your code is very difficult to read - I can almost understand dreamweaver for choking on it :)
Here is a simpler suggestion:
for($i=1; $i<=$npagine; $i++)
{
$class = ($i == $index ? "paginas" : "pagine");
echo "<a class='$class' href='index.php?$splitter_zone&index=$i'>$i</a>";
}
Not sure, but you are using the short tag for php. And it's not supported on all installs like it use to be. short_open_tag must be on to use short tags.
<?php
// bla
?>
not
<?
//bla
?>
The first thing that's wrong with it is that you should be using <?php to open your PHP tags, not just <?. The short form has been deprecated, and may not always work correctly.
Additionally, the short form <?= to print the output is deprecated. You should be using <?php print or <?php echo. (Yes, I know it makes the code longer... don't grumble about it! ;-))
This is probably what's breaking your program. New installations of PHP will choke on the short form PHP tags. Its as simple as that.
But while I'm here... The second problem you have is the horrible mixing in and out of PHP to and from HTML. You should clean up your code so that you don't have to have so many small bits of PHP. Doing it this way makes it virtually impossible to keep track of your tags in HTML and your braces in PHP. Almost guaranteed to lead to errors, and very difficult to read when you come back to it two years down the line to make a bug fix.
To solve this, I would suggest writing your code more like this:
<?php
for($i=1; $i<=$npagine; $i++) {
if($i==$index) {$class='paginas';} else {$class='pagine';}
.... //output your HTML here, without the if() condition embedded in it.
}
?>
You could simplify that even further using a ternary operator.
Switching to the long-form PHP tags <?php actively discourages excessive switching between PHP and HTML in this way, so you may want to take the opportunity to re-write your code in a more readable form.
In a case like this, there's nothing wrong with using print or echo to output the whole of the HTML tag, rather than switching to HTML mode to print it.
So you could end up with code like this:
<?php
for($i=1; $i<=$npagine; $i++) {
$class = ($index == $i) ? 'paginas' : 'pagine';
print "<a class='{$class}' href='index.php?{$splitter_zone}&index={$i}>{$i}</a>";
}
?>
Much simpler and easier to read, I'm sure you'll agree.
One final point I'd make is that I always advise to avoid using single-character variable names like $i. Try to use something more descriptive to what you're using it for. It seems harmless enough, but imagine trying to search a large program for $i to find a bug. You'd get a lot of false hits.
The PHP and HTML is fine (fsvo. "fine"; for one thing, turn off smart-tags!). Dreamweaver doesn't know how to highlight it properly.
for($i=1; $i<=$npagine; $i++) {
$class=$i==$index?"paginas":"pagine";
echo"<a class='{$class}' href='index.php?{$splitter_zone}&index={$i}>{$i}</a>\r\n";
}
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)