PHP Short If-Else

Tags: 

PHP

From this code

if($login)
  echo 'Welcome'.$username;
else
  echo 'Welcome Guest';

We can use short if-else for compact and effective by below code

echo 'Welcome '.($login ? $username : 'Guest');

Syntax of short if-else is

(condition ? right : wrong)
  • condition is the condition that return TRUE or FALSE
  • right is command that will execute if condition is TRUE
  • wrong is command that will execute if condition is FALSE

We can only put one command in short if-else or it won't be "short" anymore.

Source: http://davidwalsh.name/javascript-shorthand-if-else-examples