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.

2

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.