Home Logo
Show Full Menu
Hide Full Menu

If Statements

Created: 30/09/10 Views: 1358 myFave Image

In this tutorial we will learn If Statements
An If statement is extreemly useful for allowing your web page to be dynamic and personalised. The If Statement checks whether a statement is true or false and if it is true, it will carry out the requested command.
The If Statement is really easy to grasp once you understand how to script it and the logic behind it, and the uses are endless.
Here are some examples of its use
  • Check if a user is logged in or not
  • Check if required fields in a form are filled
  • Check if a form has been submited
  • Check if a file exists
  • Check if a password or username is correct

This is just several examples, and like I said, there are uses for this.

To write an If Statement is simple
  • if( //Condition to check ) {
  • //Requested task if condition is true
  • }
So all that is involed is the word if, brackets and curly brackets.

Here is a simple example of an If Statement
  • $name = "Frank";
  • if($name == "Frank"){
  • print "Hey Frank!";
  • }

  • Hey Frank!
So from thie example, the statement is checking if the variable 'name' is equal to (==) 'Frank', and if it is, then print "Hey Frank!", however if the statement is false, "Hey Frank!" would not have been printed

From this example you can see the Equal to is writen as == and not =, the double equals symbol refers to equal where the single equal symbol refers to setting a value.
    Here are other methods of checking
  • == Equal to
  • != Does not equal to
  • > Greater than
  • < Less than
  • >= Greather than or equal to
  • <= Less than or equal to

Copy and try for yourself!
  • $numa = 5;
  • $numb = 11;
  • if($numa < $numb){
  • print "A is smaller than B";
  • }

  • A is smaller than B

  • $answer = 9;
  • if((4+4) != $answer){
  • print "Wrong Answer";
  • }

  • Wrong Answer

This is only a few basic examples, but it should be enough for you to understand the basic method of writing an If Statement and why you would use them in your PHP scripting.

next tutorial: If Else Statement

There are no comments