Switch statements in PHP

Conditional Calculations in PHP

Many a times, we want to do something in a specific condition and entirely different thing in some other condition. To handle such type of conditional processing, PHP supports the following condition handling statements.

We will learn about these one by one.


The simplest form of a PHP if else statement is as below.


if (a==b)
Do this;
else
Do this;

Note that the statements immediately following the if or else statement are executed. If you want to execute a chunk of codes conditionally then you should include the code inside braces as given in the example below.

if (a==b) <-- Condition inside the braces
{
PHP Statement 1;
PHP Statement 2;
}
else
{
PHP Statement 3;
PHP Statement 4;
}

What if more than one statements are there? In that scenario you should use the else if statements as explained below.


The PHP syntax of an if..else if... statements are very much similar to the if...else statements. Only change here is that you validate your condition before the beginning of the else block also. The syntax is as given below.

If(a==b) <-- First condition
{
PHP Statement;
}
elseif(b==c) <-- Second condition
{
PHP Statement;
}
else <-- This block executed if above conditions fail.
{
PHP Statement;
}


If you do not like nesting and you can do away with complex conditions resulting into true or false, PHP switch is for you. The syntax of the PHP switch is as given below.


switch($var) <-- $var is the condition here
case $var=1: <-- The PHP statements are executed if $var is 1.
{
PHP Statements;
}
case $var=2: <-- The PHP statements of this case
are executed if $var is 2.
{
PHP Statements;
}

  • We use switch statements to make the code maintainable and easy to understand.
  • A switch statement begins with the keyword switch followed by the variable name in braces. After this different cases follow. These cases are chunks of codes which are executed when the value of the switch-variable($var) equals the case value(1 or 2).
  • The valid case and all subsequent cases are executed. In this sense the switch is different than traditional if else statement in PHP.
  • To avoid the subsequent cases to be executed. One should use the break statement. at the end of a case.