Last Updated: February 25, 2016
·
4.467K
· preclowski

Shorthand notations for php control structures

Option 1 - very usefull as inline

return rand(0, 1) == 0 ? true : false;

Option 2 - great for short tests

if (rand(0, 1) == 0) return true;

Option 3 - usefull when combining html and php

<?php $x = rand(0, 1); if ($x == 0): ?>
    <p>true</p>
<?php elseif($x == 2): ?>
    <p>true</p>
<?php else: ?>
    <p>false</p>
<?php endif; ?>

Bonus - other shorthands

switch (rand(0, 1):
    case 0:
        // code
    break;
    default:
        // other code
endswitch;
while (rand(0, 1)):
    // code
endwhile;
while (rand(0, 1)) echo 'foobar';
for ($i = 0; $i <= 1; $i++):
  echo $i;
endfor;

Interesting case

for($i = 0; $i <= 1; echo $i; $i++);
foreach (array('foo', 'bar') as $bar):
    echo $bar;
endforeach;
<?= 'foobar'; ?> // is same as <?php echo 'foobar'; ?> when short_open_tag directive in php.ini is enabled (unrecommended)