Skip Else statement in conditional Statment

How to skip Else statement

Hello everyone, This is my first post related to Programming.

I always love to write code with best practices and like to share one tip today which is “Skip Else statement” in Conditional statements. In programming else statement is used when we want to check for wrong condition or inverse statement. For Example:

<?php
$number = 10;
if($number == 10){
    echo "Number is 10";
}else{
    echo "Number is not 10";
}
?>

In above code first we check if number is 10, so if we want to show something or do something if number is not 10 then we will use else statement.

To Skip Else statement and also achieve our goal then we can write code like this:

Code Example:

<?php
$number = 10;
$number_check = "Number is not 10";
if($number == 10){
    $number_check = "Number is 10";
}
echo $number_check;
?>

 

In above code I skip Else statement by assigning wrong choice in variable by default and then check if number is 10 then replace that with correct statement. So if number is 10 then the If statement will run and change $number_check value to Number is 10 otherwise it default value will be Number is not 10.

Another Example:

<?php
// With Else Statement
function checkFunction($check){
    if($check == 10){
        return true;
    }else{
        return false;
    }
}

// Same function without Else Statement
function checkFunction($check){
    if($check == 10){
        return true;
    }
    return false;
}
?>

The tip for skipping Else statement is to first assume or assign value to a variable and then check for correct condition and if condition is correct then update variable with new value otherwise it’s default value will be used.

Comment if you have any question.

2 Comments

  • ali April 5, 2018 Reply

    why do we need to remove else part? what is its purposes ? thanx

    • tanseer April 5, 2018 Reply

      if/else has a potential of creating an unreadable code when not used carefully. Also it duplicates most of code in both statements which create complexity.

Leave a Reply

Read previous post:
Tanseer Hassaon Intro Coding
Welome to My Blog

Hello everyone, My name is Tanseer UL Hassan (Bangash). I am software engineer & web developer from Islamabad, Pakistan. Technologies My...

Close