PHP without fancy braces

PHP is a C-style language and thus uses fancy braces to wrap or hug control structures. PHP is also a language that is extremely flexible so you can also get by without using fancy braces. You will never get away from them entirely as functions and classes / class methods must have fancy braces and currently do not offer an alternative syntax. Let’s take a look at each of the control structures with and without braces.

If

Fancy

if ($this == $that)
{
	echo 'and like this and uh'
}

Alternate

if ($this == $that):
	echo 'and like this and uh'
endif

While

Fancy

while ($to_infinity)
{
	echo 'and beyond!'
}

Alternate

while ($to_infinity):
	echo 'and beyond!'
endwhile

For

Fancy

for ($score)
{
	echo 'and seven years ago'
}

Alternate

for ($score):
	echo 'and seven years ago'
endfor

Foreach

Fancy

echo 'He died not for men, but'

foreach ($man)
{
	echo 'If each man had been the only man made, He would have done no less.'
}

Alternate

echo 'He died not for men, but'

foreach ($man):
	echo 'If each man had been the only man made, He would have done no less.'
endforeach

Switch

Fancy

switch ($things)
{
	case 'up':
		echo 'up, up and away!'
		break

	default:
		echo 'down, down, down'
		break
}

Alternate

switch ($things):
	case 'up':
		echo 'up, up and away!'
		break

	default:
		echo 'down, down, down'
		break
endswitch

You may be asking yourself, “who codes this way?”. The fact is, I personally don’t and up until recently I had only ever seen it in WordPress templates. Recently a co-worker of mine was trying out the alternative syntax which is what reminded me that it even existed. Then Geoff Oliver of Plan8 Studios made mention to me today that the syntax looks great when you’re juggling HTML and PHP which falls in line with why it’s so predominate in WordPress Templates.

Personally, I favor fancy braces but can see the value of the alternate syntax in templates. I’d much rather see the alternate syntax than single line conditionals lacking braces entirely. Do you use the alternative syntax instead of fancy braces? Comment below and let me know!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.