Alternative syntax in PHP

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

1
2
3
<?php if ($a == 5): ?>
A is equal to 5
<?php endif; ?>

while, endwhile

1
2
3
<?php while ($a < 5): ?>
<?php print $a++; ?>
<?php endwhile; ?>

Output:

1
01234

Remember, do not use any indent in this case.

for, endfor

1
2
3
<?php for ($i = 0; $i < 5; $i++): ?>
<?php print $i; ?>
<?php endfor; ?>

Output:

1
01234

foreach, endforeach

1
2
3
<?php foreach (array(0, 1, 2, 3, 4) as $i): ?>
<?php print $i; ?>
<?php endforeach; ?>

Output:

1
01234

switch, endswitch

1
2
3
4
5
6
7
8
9
<?php switch (0): ?>
<?php case 0: ?>
<?php print 0; ?>
<?php break; ?>
<?php case 1: ?>
<?php print 1; ?>
<?php default: ?>
<?php print ""; ?>
<?php endswitch; ?>

Output:

1
0

Remember, do not use indent in any case above. All the intent will be print out as whitespaces.
Example:

1
2
3
<?php if (true): ?>
<?php print "hello world"; ?>
<?php endif; ?>

Output:

1
hello world


Other tricky things

echo, print

Both of them can let us get output

1
2
3
<?php echo "hello world"; ?>
<?php print "hello world"; ?>
<?php print("hello world"); ?>

Output:

1
2
3
hello world
hello world
hello world

print will return 1, echo won’t.

1
2
3
<?php $printReturn = print "print"; ?> // valid
<?php $echoReturn = echo "echo"; ?> // invalid
<?php print $printReturn; ?>

Output:

1
print1

Concatenate multiple arguments

1
2
3
<?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)

1
2
3
4
5
6
7
8
9
10
11
<?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

1
2
<?php $value = true && false; ?> // $value = false
<?php $value = true AND false; ?> // $value = true