fastread homefastrread library fastread menu

PHP TUTOTRIAL : Conditional Statements

Tutorial by:Manisha Dubey      Date: 2016-09-02 22:34:18

❰ Previous Next ❱

The If Statement

The PHP if statement is very similar to other programming languages use of the if statement, but for those who are not familiar with it, picture the following:

Think about the decisions you make before you go to sleep. If you have something to do the next day, say go to work, school, or an appointment, then you will set your alarm clock to wake you up. Otherwise, you will sleep in as long as you like!

This simple kind of if/then statement is very common in every day life and also appears in programming quite often. Whenever you want to make a decision given that something is true (you have something to do tomorrow) and be sure that you take the appropriate action, you are using an if/then relationship.

The PHP If Statement

The if statement is necessary for most programming, thus it is important in PHP. Imagine that on January 1st you want to print out "Happy New Year!" at the top of your personal web page. With the use of PHP if statements you could have this process automated, months in advance, occuring every year on January 1st.

This idea of planning for future events is something you would never have had the opportunity of doing if you had just stuck with HTML.

If Statement Example

The "Happy New Year" example would be a little difficult for you to do right now, so let us instead start off with the basics of the if statement. The PHP if statement tests to see if a value is true, and if it is a segment of code will be executed. See the example below for the form of a PHP if statement.

PHP Code:

$my_name = "someguy";

if ( $my_name == "someguy" ) {
	echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";

Display:

Your name is someguy!
Welcome to my homepage!

Did you get that we were comparing the variable $my_name with "someguy" to see if they were equal? In PHP you use the double equal sign (==) to compare values. Additionally, notice that because the if statement turned out to be true, the code segment was executed, printing out "Your name is someguy!". Let's go a bit more in-depth into this example to iron out the details.

  • We first set the variable $my_name equal to "someguy".
  • We next used a PHP if statement to check if the value contained in the variable $my_name was equal to "someguy"
  • The comparison between $my_name and "someguy" was done with a double equal sign "==", not a single equals"="! A single equals is for assigning a value to a variable, while a double equals is for checking if things are equal.
  • Translated into english the PHP statement ( $my_name == "someguy" ) is ( $my_name is equal to "someguy" ).
  • $my_name is indeed equal to "someguy" so the echo statement is executed.

A False If Statement

Let us now see what happens when a PHP if statement is not true, in other words, false. Say that we changed the above example to:

PHP Code:

$my_name = "anotherguy";

if ( $my_name == "someguy" ) {
	echo "Your name is someguy!<br />";
}
echo "Welcome to my homepage!";

Display:

Welcome to my homepage!

Here the variable contained the value "anotherguy", which is not equal to "someguy". The if statement evaluated to false, so the code segment of the if statement was not executed. When used properly, the if statement is a powerful tool to have in your programming arsenal!

If/Else Conditional Statment

Has someone ever told you, "if you work hard, then you will succeed"? And what happens if you do not work hard? Well, you fail! This is an example of an if/else conditional statement.

  • If you work hard then you will succeed.
  • Else, if you do not work hard, then you will fail.

How does this translate into something useful for PHP developers? Well consider this:

Someone comes to your website and you want to ask this visitor her name if it is her first time coming to your site. With an if statement this is easy. Simply have a conditional statement to check, "are you visiting for the first time". If the condition is true, then take them to the "Insert Your Name" page, else let her view the website as normal because you have already asked her for her name in the past.

If/Else an Example

Using these conditional statements can add a new layers of "cool" to your website. Here's the basic form of an if/else statement in PHP.

PHP Code:

$number_three = 3;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to true

This is a lot to digest in one sitting, so let us step through the code, line by line.

  • We first made a PHP variable called $number_three and set it equal to 3.
  • In this example we compared a variable to an integer value. To do such a comparison we use "==", which in English means "Is Equal To".
  • $number_three is indeed Equal To 3 and so this statement will evaluate to true.
  • All code that is contained between the opening curly brace "{" that follows the if statement and the closing curly brace "}" will be executed when the if statement is true.
  • The code contained within the else segment will not used.

Execute Else Code with False

On the other hand, if the if statement was false, then the code contained in the else segment would have been executed. Note that the code within the if and else cannot both be executed, as the if statement cannot evaluate to both true and false at one time! Here is what would happen if we changed to $number_three to anything besides the number 3.

PHP Code:

$number_three = 421;

if ( $number_three == 3 ) {
	echo "The if statement evaluated to true";
} else {
	echo "The if statement evaluated to false";
}

Display:

The if statement evaluated to false

The variable was set to 421, which is not equal to 3 and the if statement was false. As you can see, the code segment contained within the else was used in this case.

PHP - Elseif

An if/else statement is great if you only need to check for one condition. However, what would you do if you wanted to check if your $employee variable was the company owner Bob, the Vice President Ms. Tanner, or a regular employee? To check for these different conditions you would need the elseif statement.

PHP - Elseif What is it?

An if statement is made up of the keyword "if" and a conditional statement (i.e. $name == "Ted"). Just like an if statement, an elseif statement also contains a conditional statement, but it must be preceded by an if statement. You cannot have an elseif statement without first having an if statement.

When PHP evaluates your If...elseif...else statement it will first see if the If statement is true. If that tests comes out false it will then check the first elseif statement. If that is false it will either check the next elseif statement, or if there are no more elseif statements, it will evaluate the else segment, if one exists (I don't think I've ever used the word "if" so much in my entire life!). Let's take a look at a real world example.

PHP - Using Elseif with If...Else

Let's start out with the base case. Imagine we have a simpler version of the problem described above. We simply want to find out if the employee is the Vice President Ms. Tanner. We only need an if else statement for this part of the example.

PHP Code:

$employee = "Bob";
if($employee == "Ms. Tanner"){
	echo "Hello Ma'am";
} else {
	echo "Morning";
}

Now, if we wanted to also check to see if the big boss Bob was the employee we need to insert an elseif clause.

PHP Code:

$employee = "Bob";
if($employee == "Ms. Tanner"){
	echo "Hello Ma'am";
} elseif($employee == "Bob"){
	echo "Good Morning Sir!";
}else {
	echo "Morning";
}

Display:

Good Morning Sir!

PHP first checked to see if $employee was equal to "Ms. Tanner", which evaluated to false. Next, PHP checked the first elseif statement. $employee did in fact equal "Bob" so the phrase "Good Morning Sir!" was printed out. If we wanted to check for more employee names we could insert more elseif statements!

Remember that an elseif statement cannot be used unless it is preceded by an if statement!

PHP Switch Statement

In the previous lessons we covered the various elements that make up an If Statement in PHP. However, there are times when an if statement is not the most efficient way to check for certain conditions.

For example we might have a variable that stores travel destinations and you want to pack according to this destination variable. In this example you might have 20 different locations that you would have to check with a nasty long block of If/ElseIf/ElseIf/ElseIf/... statements. This doesn't sound like much fun to code, let's see if we can do something different.

PHP Switch Statement: Speedy Checking

With the use of the switch statement you can check for all these conditions at once, and the great thing is that it is actually more efficient programming to do this. A true win-win situation!

The way the Switch statement works is it takes a single variable as input and then checks it against all the different cases you set up for that switch statement. Instead of having to check that variable one at a time, as it goes through a bunch of If Statements, the Switch statement only has to check one time.

PHP Switch Statement Example

In our example the single variable will be $destination and the cases will be: Las Vegas, Amsterdam, Egypt, Tokyo, and the Caribbean Islands.

PHP Code:

$destination = "Tokyo";
echo "Traveling to $destination<br />";
switch ($destination){
	case "Las Vegas":
		echo "Bring an extra $500";
		break;
	case "Amsterdam":
		echo "Bring an open mind";
		break;	
	case "Egypt":
		echo "Bring 15 bottles of SPF 50 Sunscreen";
		break;	
	case "Tokyo":
		echo "Bring lots of money";
		break;
	case "Caribbean Islands":
		echo "Bring a swimsuit";
		break;	
}

Display:

Traveling to Tokyo
Bring lots of money

The value of $destination was Tokyo, so when PHP performed the switch operating on $destination in immediately did a search for a case with the value of "Tokyo". It found it and proceeded to execute the code that existed within that segment.

You might have noticed how each case contains a break; at the end of its code area. This break prevents the other cases from being executed. If the above example did not have any break statements then all the cases that follow Tokyo would have been executed as well. Use this knowledge to enhance the power of your switch statements!

The form of the switch statement is rather unique, so spend some time reviewing it before moving on. Note: Beginning programmers should always include the break; to avoid any unnecessary confusion.

PHP Switch Statement: Default Case

You may have noticed the lack of a place for code when the variable doesn't match our condition. The if statement has the else clause and the switch statement has the default case.

It's usually a good idea to always include the default case in all your switch statements. Below is a variation of our example that will result in none of the cases being used causing our switch statement to fall back and use the default case. Note: the word case does not appear before the word default, as default is a special keyword!

PHP Code:

$destination = "New York";
echo "Traveling to $destination<br />";
switch ($destination){
	case "Las Vegas":
		echo "Bring an extra $500";
		break;
	case "Amsterdam":
		echo "Bring an open mind";
		break;
	case "Egypt":
		echo "Bring 15 bottles of SPF 50 Sunscreen";
		break;	
	case "Tokyo":
		echo "Bring lots of money";
		break;	
	case "Caribbean Islands":
		echo "Bring a swimsuit";
		break; 	
	default:
		echo "Bring lots of underwear!";
		break;
}

Display:

Traveling to New York
Bring lots of underwear!

❰ Previous Next ❱


PHP TUTOTRIAL

Submit Your Thought, Tutorial, Articls etc.

Submit Your Information India's Number one online promotion website