Decision Making using IF-ELSE in php

Dear students,

today we are going to study the tools that will help you to write Decision Making Codes in php. For example, when you sign in to orkut.com you see a message ‘hello username’ on the upper right of every page. Similarly when you login to gmail if you provide wrong username or password you see an error message and if you submit accurate information you are taken to the inbox.

If you think deep on these events, this is what we call ‘decision making code’. your write intelligent code that can make decision on user’s input and can act accordingly to the input to produce required output.

PHP provides us IF - ELSE statements to write decision-making-code. Suppose I want to make a page that asks for the user’s name and password and if the username and password are wrong it displays welcome message otherwise unauthorization message.

There could be different ways to do it,

1) to read the username and password from xml file (wow! I like that!)
2) to read the username and password from text file (faster than database)
3) to read the username and password from MySQL database (or Oracle, PGSQL, MySQLi, Access)
4) to read the username and password from Excel sheets (advance)
5) Stupid way

Guess what I am going to follow? … well, method 5 … and the only reason is that you have not learnt the rest of the four methods till now therefore I have no other choice but to do it the stupid way to give you a broad understanding of IF-ELSE statements.

I am going to hardcode username and password and then check it through IF-ELSE. Let’s do it!

IF-ELSE Syntax:

The basic IF-ELSE syntax is as follow,


if(condition) {
//block of code
}
else {
  //block of code
}

If the condition that we knit together by the help of logical and comparison operators if found true then the code between IF braces will be executed otherwise ELSE code block will be taken on.

Following is the html code to get input from user.


<form action=check.php method=POST>
  Username: <input type=text name=uname size=25> <br>
  Password: <input type=password name=passwd size=25> <br>
<input type=submit value='Submit your name'>
</form>

Now let’s write the check.php code with IF - ELSE


<?php
  
//predefined values
$user="haroon";
$pass="ilovephp";
 
//fetch values from POST array
 
$userName = trim($_POST['uname']);
$password = trim($_POST['passwd']);
 
//using IF - ELSE with the help of comparison and Logical operators
 
  if($userName == $user && $password == $pass) {
   echo "Authorization Accepted!";
  }
   else {
     echo "Authorization Rejected!";
  }
?>

TRIM FUNCTION:

trim function is used to remove blank spaces from start and end of the variable values to ensure user is not filling blank form with spaces or unintentionally may have pressed blank spaces. It is handy to apply this function while receiving form values.

Fetching Values From Global Arrays:

There are two ways to fetch variables from sending page

1) directly be refering to the variable name
2) using global arrays ($_POST,$_GET)

it depends on your php.ini settings if the GLOBAL settings are ON then you can refer to the variable name directly otherwise you have to use Global arrays.

I’d recommend the use of global arrays because mostly server’s configure php to switch of the global variables for security reasons and it is better to fetch values using global arrays so that your code can run on different servers with different php configurations without any crash.

Multiple IF-ELSE using elseif:

you can use more than one set of if else as follow,


if(condition)
//code here
elseif (condition)
code here
elseif(condition)
//code here
else
code here

you can write multiple sets of IF-ELSE for example if you are asked to make a resultsheet for the students and to calculate the grade depending on the percentage so you will need more than one IFs. ELSEIF is used to attach a second IF condition with the previous IF so that if the previous IF is false the code will check the next IF. Remember if the first IF statement is true then control will not come to the remaining IFs or Else. Last else is executed if all IF and elseif conditions are false.

Also you have may noticed that I didn’t use opening and closing braces for IF and ELSE it is because when you have single line after IF or ELSE then it is not necessary to put opening and closing braces however it is a good practice to put them. However if you have more than one lines code for IF or ELSE then you must use braces to make block of code otherwise control will skip all lines after the first line of IF or ELSE e.g


if(condition)
echo "i am first line";
echo "i am not executed";

now the control will execute the first line only if the condition is true and will skip the second line so the accurate way to do it is,


if(condition) {
echo "i am first line";
echo "i am not executed";
 
//the above both lines will execute now because they are blocked within braces
 
}

Also it is not necessary to use else statement all the time with IF it totally depends on your requirements if you need ELSE then put it otherwise IF will work alone BUT ELSE doesn’t work alone you must have an IF statement before using ELSE

Assignment: Make a result-sheet system based on two pages,

a) score page: in this there should be five fields where user can submit number in five different subjects

b) result page: this page will receive the form and will display total numbers, grade and percentage based on the submitted score.

You can email me your assignments or post in comments to this thread.

In the next articles I will show you how to use SWITCH statement for Decision Making Code.

Till then take good care of yourself and practice.

- Haroon Ahmad

4 Comments

  1. haroon.ahmad said,

    January 20, 2007 at 2:08 pm

    there is a confusion among a few about the following example,

    if(condition)
    echo “i am first line”;
    echo “i am not executed”;

    the above code doesn’t mean that the second line will never be executed. One should interpret this example with context to my explanation of IF statement before this example.

    I have not posted exact code but it’s kinda pseudo code to explain that if you are not making block of code using braces for your IF statement then the first line after IF will be executed as the part of IF statement and the lines following will not be executed as the part of IF though the control will go to them.

    therefore to execute more than one line as part of IF statement you should use braces to make block of code.

  2. Articles Repository » Blog Archive » Loops in PHP said,

    January 20, 2007 at 11:52 pm

    […] FAST PHP Tutorial (Part 1) How to Install PHP on Windows (Fast PHP Tutorial Part 2) How To Install PHP On LinuxHow To Install Apache on WindowsEasy Installers to Install PHP, MySQL, Apache on Windowshttp://fastcreators.com/article/2007/01/09/php-programming-basics/Operators in PHPDecision Making using IF-ELSE in phpDecision Making using PHP Switch Statement […]

  3. Articles Repository » Blog Archive » Detailed Guide To Arrays In PHP said,

    January 29, 2007 at 1:01 pm

    […] FAST PHP Tutorial (Part 1) How to Install PHP on Windows (Fast PHP Tutorial Part 2) How To Install PHP On Linux How To Install Apache on Windows Easy Installers to Install PHP, MySQL, Apache on Windows PHP Programming Basics Operators in PHP Decision Making using IF-ELSE in php Decision Making using PHP Switch Statement Loops In PHP […]

  4. mariah maganoh said,

    September 17, 2008 at 8:23 pm

    help me out in creating a form using php arrays as follow:

    Member Registration
    Username
    Password

    1. The username should only accept numbers and letter
    2. The password should be at least 6 characters

    * These checks should be done when the logon button is clicked.

Post a Comment

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word