Credit portal




The If Statement

what if statements

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:

Advertise on

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:


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.

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:


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!

Download's PHP Book

Category: Forex

Similar articles: