0

Can someone please explain to me the use of alternative syntax I often come across when looking at php usage in word press. Take conditionals for example:

I expect to see:

if(10==10)
echo 'this is true and will be shown';

Instead, I see:

if(10==10):
echo 'this is true and will be shown;
end if;

And another example:

! empty ( $classes_names ) 
and  $class_names = ' class="'. esc_attr( $class_names ) . '"';

Whats with the ':' the 'end if;' and the last examples syntax is not something I have seen before put together like that.

BIOS
  • 1,655
  • 5
  • 20
  • 36
  • 2
    [Difference between if () { } and if () : endif;](http://stackoverflow.com/questions/564130/difference-between-if-and-if-endif) – Chris Aug 22 '12 at 09:48
  • Succinct an explanation as I've seen. Thanks. – BIOS Aug 22 '12 at 10:08

1 Answers1

6

This is the alternative logic syntax in PHP - you can read all about it here - http://php.net/manual/en/control-structures.alternative-syntax.php

If you are including conditional statements in amongst HTML or other code then it makes things look a lot neater.

For example:

<body>
<? if($_GET['name']=='Dave') {?>
<h3>Hello Dave!</h3>
<? } else { ?>
<h3>Hello Stranger!</h3>
<? }?>
</body>

Looks much nicer IMO as:

<body>
<? if($_GET['name']=='Dave'):?>
<h3>Hello Dave!</h3>
<? else:?>
<h3>Hello Stranger!</h3>
<? endif;?>
</body>

As for the final code example - this is another way of writing an if statement - so this:

<? !empty ( $classes_names ) and  $class_names = ' class="'. esc_attr( $class_names ) . '"';?>

Is the same as:

<? 
if (!empty($classes_names)){
$class_names = ' class="'. esc_attr( $class_names ) . '"';
}
?>

That is definitely confusing for sure!

DaveR
  • 2,355
  • 1
  • 19
  • 36
  • Ah great. Hopefully soon it will stop looking weird. Agreed it looks nicer when you are jumping in and out of the php! And what about the final code example? How exactly is that statement evaluated? – BIOS Aug 22 '12 at 10:05