Web Info and IT Lessons Blog...

Wednesday 5 November 2014

If/Else Statements in PHP

The previous lesson of PHP Lessons Series was about PHP Operators. In this lesson we will learn the IF/ElSE statements in PHP.

If Else Example

IF/ElSE statements are basic and very important in all programming languages. These are conditional statements used to execute a block of code when a condition is true. Below is the basic flow of an if/else code execution:

if(condition true){
 Execute this chunk of code
}else if(condition true){
 Execute this chunk of code
}else if(condition true){
 Execute this chunk of code
}else{
 Execute this chunk of code
}

In the above sample code all the conditions will be checked top to bottom one by one until a condition is true, when a condition is met the code inside that condition will be executed and no more conditions after that will be checked. For a better understanding,let us write a program to print the age group of a person based on the age of the person.

$age = 25;
if($age <= 4){
 echo 'You are an infant';
}else if($age > 4 && $age <= 12){
 echo 'You are a child';
}else if($age > 12 && $age <= 19){
 echo 'You are a teen';
}else if($age > 19 && $age <= 40){
 echo 'You are an adult';
}

In the above code we have set the value of variable $age = 25 and applied conditions on $age to calculate the age group. Just play with the value of $age for different age groups. There will be only one output for a particular value of $age, as when the first age group condition is met no more conditions after it will be checked.

If/Else Statements in PHP using Ternary Operators:


The basic syntax of an if/else statement using ternary operators is like this:

(condition ? if true do this: if false do this); 

In the above sample code if the condition provided is true, then the code written after (?) operator will run and if the condition is false, then the code written after (:) operator will run. For better understanding consider the code below:

$age = 50;
echo ($age <= 50 ? 'You are Young': 'You are old');

The above code checks if $age is less than or equal to 50 then it outputs 'You are Young' and if $age is greater than 50 then it outputs 'You are young'.


No comments:

Post a Comment