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:

<?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.

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.

Leave a Reply