Decision Making in PHP

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Decision Making in PHP
PHP like most other languages provides decision making tools with the help of those you can exceute something if some condition is true.

if:
Using if you can execute statement or staements only if expression(or condition) is true

    if(condition)
    {
        statements; // Will only be executed if condition is true
    }


else:
else is always used with if and has the statements which need to be executed if the condition is not met.

    if(condition)
    {
        statements; // Will only be executed if condition is true
    }
    else
    {
        statements; // executed when condition is not true
    }

You can use if without else but not the other way around.

elseif
When you have more than one conditions and have diffrent sets of statements to be excuted for diffrence condition.

    if(condition1)
    {
        statements; // Will only be executed if condition1 is true
    }
    elseif(condition2)
    {
      statements; // when condition1 is false but condition2 is true
    }
    else
    {
        statements; // executed when none of conditions are true
    }

You may use as many elseif as you want.

switch
When the conditions are the values of a particular variable you can use switch statement. Swich statement can have cases depending on the values of a variable.

    switch($var)
    {
      case value1:
            statements; // when $var = value1
            break;
      case value2:
            statements; // when $var = value2
            break;
      case value3:
            statements; // when $var = value3
            break;

    }

Here is a program that will help you better understand the decision making process in PHP

<?php
  $a=10;
  $b=12;
  if ($a==$b) {
  	echo "both are equal<br>";
  }
  elseif ($a>$b) {
  	echo "a is greater than b<br>";
  }
  else {
  	echo "b is greater than a<br>";
  }

// Usage of switch statement
  switch ($a) {
  	case 10:
  		echo "Its 10<br>";
  		break;
  	case 20:
  		echo "Its 20<br>";
  		break;
  	default:  // default executes when none other case is satisfied
  		echo "Its neither 10 nor 20";
  		break;
  }

?>


Output
b is greater than a
Its 10

Login to Track Your Progress