Ok, pun-y title is and was 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.

1
2
3
if(condition):
    //statements   
endif;

IF-ELSEIF-ELSE conditional construct.

1
2
3
4
5
6
7
if(condition) :
        //statments
    elseif(condition) :
        //statments
    elseif(condition) :
        //statments
endif;

IF Statement in one line

1
 print $eatit = ($apple !=”green”) ? “Eat” : “Dont Eat”;

SWITCH conditional construct.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
switch($var):
    case 1:
        //statements
        break;
    case 2:
        //statements
        break;
    case 3:
        //statements
        break;
endswitch;

WHILE loop construct

1
2
3
while(condition):
	//statements;
endwhile;

FOR loop construct

1
2
3
for(exp):
	//statements;
endfor;

FOREACH loop construct

1
2
3
foreach(exp):
    //statements;
endforeach;

ECHO statement

1
 <?= $var; ?>
is same as
1
   <? echo $var; ?>

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! Reach out, and let me know!