For now you should be quite comfortable with variables, data types and operators, but these are still not enough for a PHP programmer. As a programmer, you may run into situations in which you want a line of codes to execute only if certain conditions are match. Lets consider a simple example here:
PHP Code:
$age < 1 => Infant
1 < $age < 3 => Toddler
3 < $age < 11 => Child
11 < $age < 18 => Teenager
$age > 18 => Adult
If you want to display a person's age group based on how old he/she is, you will have to use a conditional statement. There are basically three types of conditional statements you can manipulate in PHP:
If...else statement
Switch...case statement
? operator statement
1. If...else statement:
If...else statement is the basic conditional statement whose usage is universal among all programming languages. I've learned C++ and Ruby prior to PHP, and tbh I see no big difference in their syntax for if...else statement. The basic structure of If...else statement is:
PHP Code:
if(A boolean expression){
// codes to execute if the expression evaluates as true
}
else{
// codes to execute otherwise
}
The syntax of an If...else statement is quite easy to remember. The parenthesis following key word
if encloses a boolean expression of any possible complexity, and the codes to execute must be entered within brackets. The else statement, on the other hand, is not required but recommended. It does not enclose any boolean expressions, since PHP knows that it needs to execute its content if the boolean expression above is evaluated false. An example of If...else statement can be viewed below:
PHP Code:
$age = 13;
if($age < 18){
echo "This is a teenager!";
}
else{
echo "This is an adult!";
}
The screen displays the message "This is a teenager!", just as many of you may have expected. Looks easy? Well, we can definitely try to complicated our lives by adding more than one boolean expressions to the conditional branch. This time we will have to use
elseif(), whose syntax is almost identical to if(). Note elseif statement only executes when its boolean expression enclosed in parenthesis evaluates as true, and that the expressions above are evaluated false. An example is shown below:
PHP Code:
$age = 2;
if($age < 1){
echo "This is an infant";
}
elseif($age >=1 and $age <=3){
echo "This is a toddler";
}
elseif($age > 3 and $age < 11){
echo "This is a child";
}
elseif($age >=11 and $age < 18){
echo "This is a teenager";
}
else{
echo "This is an adult";
}
Not surprisingly, the screen prints "This is a Toddler". The logic behind this is quite simple. The expression in if statement is evaluated false, and thus PHP skips the codes within its brackets. The second expression in elseif statement is evaluated true, so the entire codes inside brackets are executed. PHP proceeds to skip the rest of lines since the second boolean expression is already true. If none of the four expressions are true, the script will finally reach our else statement.
Advanced programming may require multiple if...else statements enclosed in one if...else statements. Logic becomes quite important at times like this, and it is rather easy to leave out a bracket that leads to fatal errors in your script file. Be careful when you see a huge number of if...else statements in a php file, keep in mind that the total number of left brackets should always be equivalent to the number of right brackets. A complicated PHP script of this type is written below:
PHP Code:
$score = 87;
if($score <= 100 and $score >= 90){
echo "Excellent!";
if($score >= 94){
echo "</br>Your grade is A!";
}
else{
echo "</br>Your grade is A-";
}
}
elseif($score < 90 and $score >=80){
echo "Good!";
if($score >=87){
echo "</br>Your grade is B+";
}
elseif($score >=83 and $score <87)
echo "</br>Your grade is B";
else{
echo "</br>Your grade is B-";
}
}
elseif($score < 80 and $score >=70){
echo "You did so so!";
if($score>=77){
echo "</br>Your grade is C+";
}
elseif($score >=73 and $score < 77){
echo "</br>Your grade is C";
}
else{
echo "</br>Your grade is C-";
}
}
elseif($score <70 and $score >=60){
echo "You barely passed this exam";
if($score>=67){
echo "</br>Your grade is D+";
}
elseif($score>=63 and $score<67){
echo "</br>Your grade is D";
}
else{
echo "</br>Your grade is D-";
}
}
else{
echo "You did pretty bad, it is an F";
}
The screens displays "Good! Your grade is B+", as we have expected. You may vary the value stored in variable $score to get a better feel of how the logic flows in this script.
2. Switch...case statement:
Another popular conditional statement is this Switch...case. If used properly, it significantly simplifies your codes and gives a much better and more organized looking. Switch...case statement also runs much faster than if...else statement, and thus is highly recommended for programmers running popular virtual pets sites. The syntax for Switch...case statement is:
PHP Code:
switch(expression){
case result1:
//your codes for the first possible outcome
break;
case result2:
//your codes for the second possible outcome
break;
case result3:
//your codes for the third possible outcome
break;
... ...
default:
//your codes for a default outcome if none of the above conditions are met
}
The expression is usually a variable, which can be of even arrays or objects. PHP then runs through the entire conditional branches to find results that matches this particular expression. The codes right below
case result: are executed if it matches our expression defined earlier in this statement. If nothing is matched, the last term
default: shall execute. A good example is shown below:
PHP Code:
$grade = "C";
switch($grade){
case "A":
echo "You did excellent, you outperformed 95% of your classmates!";
break;
case "B":
echo "You did a good job, it was better than average!";
break;
case "C":
echo "You did just fine, but could be even better!";
break;
case "D":
echo "You did not get a good grade, try much harder next time!";
break;
default:
echo "I am afraid you will have to take this course again...";
}
The result is, undoubtedly, "You did just fine, but could be even better!", exactly as what would happen if you get a grade C. You may wonder what the line
break; does in this script. Lemme get rid of all of them and see what happens:
PHP Code:
You did just fine, but could be even better!You did not get a good grade, try much harder next time!I am afraid you will have to take this course again...
Astonishingly, PHP executes all lines below
case "C", which is a basic property of this switch...case statement. Without the usage of break, the script continues to run till the very end. This is why programmers must be real cautious with switch...case statement so they wont forget all these breaks.
A down side of switch...case statement is that it is not good to use if you have a long expression awaiting evaluation. In cases like this, it is better to go back to our if...else statement. Switch...case statement, however, does simplify our codes to a certain extent. I will be using it frequently when coding an itemshop, and you will see how powerful tool it can be.
3. ? operator statement:
Switch...case statement already simplifies our script files considerably, but there's another technique that you can apply to make even fewer and neater lines in your PHP codes. The ? operator may seem hard to understand at first, but they are quite good to use. Its syntax is:
PHP Code:
(expression)?result_if_returns_true:result_if_returns_false
This way we get rid of all those annoying brackets and make a compact form of PHP codes in one single line. An example of ? operator statement can be viewed below:
PHP Code:
$age = 16;
$conclusion = ($num > 18 or $num < 11)?"He/she has passed or yet to enter Puberty":"The kid is currently in his/her puberty";
echo $conclusion;
The result is "The kid is currently in his/her puberty", as you may have imagined. The ? operator is used in advanced programming, and it runs even faster on web server than switch...case statement. The only problem with ? operator is that it can only be used when you have two opposite outcomes regarding an expression. It cannot be further extended to three or more conditions, unfortunately.
And thats the end of it, you've learned basically everything about conditional statements in chapter 3. They are rather convenient to use and easy to identify in programming, but too many conditional branches makes your script files messy. To solve this problem, we use loops that will be introduced in next chapter. I hope you have all understood the basis of PHP programming at this point now, and I'd strongly recommend you to go back and review the previous lessons if you are still stuck with these fundamental concepts. Enjoy!
Hall of Famer