PHP conditionals, brackets needed?

you can do if else statements like this:

<?php
if ($something) {
   echo 'one conditional line of code';
   echo 'another conditional line of code';
}


if ($something) echo 'one conditional line of code';

if ($something)
echo 'one conditional line of code';
echo 'a NON-conditional line of code'; // this line gets executed regardless of the value of $something
?>

and then you can also write if – else in an alternate syntax:

<?php
if ($something):
   echo 'one conditional line of code';
   echo 'another conditional line of code';
elseif ($somethingElse):
   echo 'one conditional line of code';
   echo 'another conditional line of code';
else:
   echo 'one conditional line of code';
   echo 'another conditional line of code';
endif;
?>

with the alternate syntax you can also fall out of parsing mode like this:

<?php
if ($something):
?>
one conditional line of code<br />
another conditional line of code
<?php
else:
   echo "it's value was: $value<br />\n";
?>
another conditional line of code
<?php
endif;
?>

But this gets really messy really fast and I won’t recommend it’s use (except maybe for template-logic).

and to make it complete:

<?php
$result = $something ? 'something was true' : 'something was false';
echo $result;
?>

equals

<?php
if ($something) {
   $result="something was true";
} else {
   $result="something was false";
}
echo $result;
?>

Leave a Comment