Learn to break the line of flow with If-Else in PHP

Programming becomes so easy when we have to follow a straight path, as in life we all dream of a comfortable existence without any distractions, deviations and obstacles. Unfortunately life has a bad habit of throwing surprises when we least expect them, similarly when a developer sits with a great mood and listens to the requirements of the client and finds the spirits dampening with the possibilities of programming flow going haywire. Normally programmers, most of the time, anticipate complex situations. They are comforted by the fact that programming languages like PHP have equipped them with enough weaponry in the form of control flow statements and functions to help tackle any type of complicated coding challenges. Only attributes required to write a good software program are a logical mind and expertise with all the nuances of at least one programming language.

Such deviations from the straight flow, while programming, are handled by control flow statements. If-Else is one such control flow, which is also rightly referred to as a decision making statement. As evident from the name, this statement helps you make decisions on where the flow will proceed, depending upon the execution of some conditions. Let us first look at the syntax of a simple If statement,

If (operand1 operator operand2) execute this statement if true

Here operator, between the two operands, is a comparison operator. If the value of the condition specified in the parenthesis turns out to be 1 or True then statement under it will get executed.

 

Let us look at the various comparison operators,

Equal to ==
Not Equal to != or <>
Greater than >
Less than <
Great than or equal to >=
Less than or equal to <=
Equal to with data types matching ===
Not equals to or datatypes are not same !==

Let us see an example of a very simple If statement,

If ($marks >=  90) echo "Congratulations! You have got A+ grade!!";

As you can see above, if a student scored marks greater than 90 out of say 100 then the congratulation statement under it will be displayed. But if marks were less than 90 then nothing will be displayed.

So far so good but what if we want to display a message for those candidates who did not get A+ grade. In that case we will have to introduce a second message in the above example if the main condition is not satisfied. This can be done through the else construct being added to the above example, making it a perfect if-else statement. Let us modify the above example a bit to explain how a second message for those not getting A+ grade can be displayed through the else,

If ($marks >=  90) echo "Congratulations! You have got A+ grade!!";
Else echo "Sorry you could not make it to the top grade this year";

So this is your first baby step towards programming complex flows.

Author: ucavik


»