Categories
PHP Programming Wordpress Development

PHP Alternative Syntax

Did you know that PHP has an alternative syntax structure?  Up until about two years ago, I didn’t either.  It wasn’t until I started poking around in the WordPress core that I saw it.  Intrigued, I popped over to PHP.net and read an entry on it.  In a nutshell, the alternative syntax can go far in making your PHP code much easier to read.  The control structures if, while, for, foreach, and switch can all be expressed in the alternative syntax form.  In general, I prefer to use the alternative syntax when mixing PHP in with HTML, and the standard syntax when writing pure PHP.

If Example

// This....
if($myString == "foo"):
    echo "bar";
else:
    echo "no-foo-bar";
endif;
 
//...is equal to this.
if($myString == "food") {
    echo "bar";
} else {
    echo "no-foo-bar";
}

ForEach Example

$names = array("bob", "tom", "john");
 
//This....
foreach($names as $name):
    echo "Your name is: {$name}";
endforeach;
 
//...is equal to this.
foreach($names as $name) {
    echo "Your name is: {$name}";
}

Resources

If you’re looking for more resources on PHP’s alternative syntax, check out the documentation here, or the WordPress source code for examples.

By Jack Slingerland

Founder of Kernl.us. Working and living in Raleigh, NC. I manage a team of software engineers and work in Python, Django, TypeScript, Node.js, React+Redux, Angular, and PHP. I enjoy hanging out with my wife and son, lifting weights, and advancing Kernl.us in my free time.

2 replies on “PHP Alternative Syntax”

Seriously: colons versus squirrelly-brackets?

I don’t see that either form “can go far in making your PHP code much easier to read” unless the person reading it is wedded to Perl/C-style syntax versus Perl syntax.

-danny

Thanks for sharing! I’m learning PHP and any new viewpoint is appreciated.

-Tony

Comments are closed.