Skip to content

PHP Condition Statements: Shorthand, Nested, Inside function

Share Button
 <?php

/** Declare String Variable  */
$name = "Kwacho";

/** 
*   #1  
*   Regular  
*/
if($name){
    echo $name;
} else {
    echo "....Oopsy";
}

/** 
*   #2  
*   Alternate Syntax 
*/
if($name):
    echo $name;
else:
    echo "....Oopsy";
endif;

/** 
*   #3
*   Shorthand 
*/
$shortHand = ($name ? $name : "....Oopsy");
echo $shortHand;

/** 
*   #4  
*   Nested 
*/
if($name){
    if($name=="Kwacho"){
        echo $name;
    }
}else{
    echo "....Oopsy";
}

/** 
*   #5  
*   Nested Shorthand 
*/
$nestedShortHand = ($name ? ($name=="Kwacho" ? $name : ""):  "Name is not Kwacho");
echo $nestedShortHand;

/** 
*   #6  
*   Shorthand condition statement within function : Resolves to 1 as $name var is a string.
*/
echo is_string($name ? $name : "");


/** 
*   #7  
*   No Brackets  - Only first statement will be treated as a body of the condition
*/
if($name)
    echo $name;
?>
Share Button