Conditions in PHP

Conditions in PHP are most important to understand as most programming depends on the condition. Whenever we need to decide whether we run this code or not we make a condition. Let's consider a student grading system to understand conditions we will use fix number to understand fast.

$total_marks= 100;
$obtain_marks= 70;
$percent= (70 / 100) * 100; // formula to get percent (obtain/total) * 1oo

above i just defined the formula to get a student percentage to make an example so easy to understand condition usage. Now $percent containing the percent when we working in a program there should not fixed value of $obtain_marks so percentage will vary with values of this variable but now we are using fixed value that is 70 and output of formula will be 70 its mean student gets 70% marks.

Let's move to our real topic conditions in php. First decide only pass/fail with simple (if) condition.

if($percent < 33){
echo("You are FAIL");
}

if we see above code, it is just like

if(condition){ code block}

If we run above condition, we get nothing. 🙂 Why? Actually, on condition we are saying that if percentage is less than 33 then print "You are FAIL" but in our current case we have 70 values so this condition is not True and code block will not run and nothing prints. Our use of condition has no issue (no sentence error) but our logic does not cover both cases for this we will use condition like below.

if($percent < 33){
echo("You are FAIL");
}
else{
echo("You are PASS");
}

Now we are covering both ends if less than 33 then print FAIL line otherwise PASS line will be printed. Let's move forward on conditions in php there we also need to make grade like A, B, C or more. Consider C grade will be under 60 percent, B grade under 80 percent and A grade under 100 percent. Here we need to nest if block as much as need to cover all percentages.

if($percent < 33){
echo("You are FAIL");
}
else if($percent <= 60){
echo("You are PASS and get grade C");
}
else if($percent <= 80){
echo("You are PASS and get grade B");
}
else if($percent <= 100){
echo("You are PASS and get grade A");
}

We can use else with else if block but in current case it is not required now if percent is less than 33 then FAIL line run if less than or equal 60 then C grade print and so on.

One point is important to understand whenever a condition is true in nested if blocks it stop working and don't check remaining if conditions e.g., in current case we have 70% so B grade line print and next condition will not check even. One more point we cannot start from end in this case like

if($percent <= 100){
echo("You are PASS and get grade A");
}

If we start from the top then the first condition is always true, like if the percentage is 10% then it is less than 100 so first block is run always and we never get real grade in this case.

These are some basic concepts of conditions in php I will write more article to cover remaining concepts in this top. Thanks