Alternative syntax in PHP
In PHP, there are a lot of alternative syntax. It can improve the legbility of your code.
if, while, for, foreach, switch
The alternatice syntax in control structures is to remove the openning brace instead of a colon and closing with endif, endwhile, endfor, foreach, and endswitch.
if, endif
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>
while, endwhile
<?php while ($a < 5): ?>
<?php print $a++; ?>
<?php endwhile; ?>
Output:
01234
Remember, do not use any indent in this case.
for, endfor
<?php for ($i = 0; $i < 5; $i++): ?>
<?php print $i; ?>
<?php endfor; ?>
Output:
01234
foreach, endforeach
<?php foreach (array(0, 1, 2, 3, 4) as $i): ?>
<?php print $i; ?>
<?php endforeach; ?>
Output:
01234
switch, endswitch
<?php switch (0): ?>
<?php case 0: ?>
<?php print 0; ?>
<?php break; ?>
<?php case 1: ?>
<?php print 1; ?>
<?php default: ?>
<?php print ""; ?>
<?php endswitch; ?>
Output:
0
Remember, do not use indent in any case above. All the intent will be print out as whitespaces. Example:
<?php if (true): ?>
<?php print "hello world"; ?>
<?php endif; ?>
Output:
hello world
Other tricky things
echo, print
Both of them can let us get output
<?php echo "hello world"; ?>
<?php print "hello world"; ?>
<?php print("hello world"); ?>
Output:
hello world
hello world
hello world
print will return 1, echo won’t.
<?php $printReturn = print "print"; ?> // valid
<?php $echoReturn = echo "echo"; ?> // invalid
<?php print $printReturn; ?>
Output:
print1
Concatenate multiple arguments
<?php echo "hello ", "world", "\n"; ?>
<?php echo "hello " . "world" . "\n"; ?>
<?php print "hello " + "world" + "\n"; ?>
In addition, <?="hello world"?>
will be treated as<?php echo "hello world" ?>
.
Print and echo roughly have same speed, so if you use one over the other, it may not improve the performance of your application.
if (isset($value)), if ($value)
<?php if (isset($value)): ?> // It will only check whether you defined that variable.
...
<?php endif; ?>
<?php if ($value): ?> // It can be used only if you have defined the variable. If it is default value, return false.
...
<?php endif; ?>
// 0, false, "" are default values.
<?php $value = 0; ?>
<?php if ($value): ?> // false
<?php endif; ?>
AND - &&, OR - ||
&&, ||
have higher priority than AND, OR
<?php $value = true && false; ?> // $value = false
<?php $value = true AND false; ?> // $value = true