Ok, the title pun, is intended.
When I started out with PHP, every project I worked on required me to keep typing incessantly, not that I don’t like my keyboard or the keys on it, but sometimes the syntax does get to you, especially if you are write code in various scripts and languages and not to mention the missing/dangling braces!
I started to research PHP based alternative syntaxes to help me with preserving my keyboard and my sanity. So I learnt how not use braces and that PHP actually has an alternative syntax that you can use. In fact if you write a lot PHP, using different frameworks and what not, you should look into this. Some frameworks use the alternative syntax and some don’t. Might save you some time.
Here are some PHP alternative syntax and shorthand techniques.
IF-ELSE Conditional Construct.
if(condition): //statements endif;
IF-ELSEIF-ELSE conditional construct.
if(condition) : //statments elseif(condition) : //statments elseif(condition) : //statments endif;
IF Statement in one line
$apple = "green"; print $eatit = ($apple !=”green”) ? “Eat” : “Dont Eat”;
SWITCH conditional construct.
switch($var): case 1: //statements break; case 2: //statements break; case 3: //statements break; endswitch;
WHILE loop construct
while(condition): //statements; endwhile;
FOR loop construct
for(exp): statements; endfor;
FOREACH loop construct
foreach(exp): //statements; endforeach;
<?= $var; ?>
is same as
Why should you use PHP shorthand / Alternative Syntax?
- Saves time with the ternary operators used in the if statement.
- Saves your sanity, if you are writing 100s of lines of code, alternative syntax does help with the braces, ALOT!
- Great to understand and debug.
- End makes it easier to know which control structure is ending as compared to counting braces.
- Reduces the size of code/file.
If you know any more short cuts or have suggestions, corrections please do help! Comment and let me know!