PHP Switch case

PHP Switch case statement is an alternative for complex IF statements with a same expression. Its a best alternative for elseif statements using the same expression.
In many situations we need to compare a variable against different values and needs different operations according the values. Switch statement is coming for this requirement.

See the syntax structure of switch case statement in a PHP program

switch ($variable){

case $value1 :
Operation statements for this value1;
case $value2:
Operation statements for this value1;
case $value3:
Operation statements for this value1;
default:
Operation statements when there is no match in all the above cases;
}

Working of a switch case statement
switch statements is executed by line by line. No code will execute till the first match case found. After that it will execute all other case codes till a break statement found.Its really important to understand this behavior to avoid mistakes with this statement.

Usage of break statement in switch case
Break statement is used if we want to stop the execution of other cases when one case match with our condition.
See the difference in ouput for the following two sample programs

<?php
$i=1;
switch ($i) {
case 0:
echo " 0 ";
case 1:
echo " 1 ";
case 2:
echo " 2 ";
default:
echo " NO MATCH ";
}
?>

Its output will be
1 2 NO MATCH
Here we can see that, after the match case found ( in this case 1 ) all other case codes also executed. We need to use the break statement to avoid this.

<?php
$i=1;
switch ($i) {
case 0:
echo " 0 ";
break;
case 1:
echo " 1 ";
break;
case 2:
echo " 2 ";
break;
default:
echo " NO MATCH ";
}
?>

Its output will be ;
1
Here we can see that program stops the execution of other case statements due to the break statement in matched case.

Switch case statements supports strings also. See the following sample PHP program with switch case dealing with strings.

<?php
$i="PHP";
switch ($i) {
case "ASP":
echo " I hate ASP ";
break;
case "VB":
echo " Its good but I dont want ";
break;
case "PHP":
echo " I Love PHP ";
break;
default:
echo " NOTHING ";
}
?>

Its output will be :
I Love PHP
( Note : strings should be enclosed in double quotes)

call function in PHP

We can create our own function inside our PHP programs for re-usability and making our code optimization purposes. Functions are a block of codes executed only when calling. Codes inside a PHP function will execute when we call a function in PHP program.

We can create a function using the “function” statement. Its syntax will look like

function functioname()
{
Operation Codes here;
}

Here is a simple example of using a function in PHP

<?php
function message()
{
echo "Welcome to phpmysqlbrain.com";
}
$name="Guest";
echo "Hi ".$name." ";
message();
?>

Its output will be
Hi Guest Welcome to phpmysqlbrain.com
You can easily understand whats happening when we call that function.

Now we can look at some more deep about functions. We can use parameters to pass the values to a function. Also function can return the values ( results ).

See the following sample PHP program for passing a value to a function

<?php
function message($data)
{
echo "Hi ".$data." Welcome to phpmysqlbrain.com";
}
$name="Guest";
message($name);
?>

Its output will also same as our previous example
Hi Guest Welcome to phpmysqlbrain.com
Here we can see that we have passed the $name variable to the function message() . And function received that variable using the variable $data. Like this we can pass any number of parameters while calling a function.

Now watch the following sample PHP program with passing more than one parameters and return value from a function

<?php
function multiply($a,$b)
{
$result=$a * $b;
return $result;
}
$x = 10;
$y = 20;
$z = multiply($x,$y) + 1;
echo $z;
?>

Output of this program will be:
201

Here call multiply function passing the values $x and $ y. function multiply receiving these values with variables $a and $b accordingly. Then its doing the calculation parts and return the result.

Array in PHP tutorial

Array is a special variable which can store multiple value. ( Note : a normal variable can store only one value at a time ). Arrays are the oldest and most important data structure which can hold multiple values. Each value in an array is associated with a key. And we can retrieve each value from array using the keys.

Arrays can be mainly two types

  • One-dimensional arrays
  • Multidimensional arrays

Array in PHP can be categorized as

  • Numeric arrays
  • Associative array
  • Multidimensional array

In PHP array can be declared using the construct array()

Numeric arrays are with a numeric index. Here we don’t need specify the keys. Index will start from 0. Means first data can be accessed using the index 0 , second data can be accessed using the index 1 etc
See the Example for a numeric array declaration
$names=array(“Syam”,”Binu”,”Bob”,”cathy”);
Its same as the following declarations
$names[0]=”Syam”;
$names[1]=”Binu”;
$names[2]=”Bob”;
$names[3]=”cathy”;

In Associative arrays each key is associated with a value.Here we need to specify each key and its associated value. And these values can be fetched using the declared keys.
See the example of an Associative array declaration
$age = array(“Syam”=>30, “Binu”=>25, “Bob”=>50, “cathy”=>30);
Here Syam, Binu etc are the keys and values are associated with those keys using => .
In this example we are trying to store the ages of some persons using arrays. So if we want to know the age of one particular person , we only need to know his name ( key ).
The above array can be declared same as
$age[“Syam”]=30;
$age[“Binu”]=25;
$age[“Bob”]=50;
$age[“cathy”]=30;

In Multidimensional arrays each element in array can be another array. Its useful for building matrices, tree and table like data storage structures.In some programming scenarios we can avoid the usage of several different one-dimensional arrays using a single Multidimensional arrays for our programming optimization , speed and other things.

For example , consider a case we need to store names , age and location. We can use a multidimensional array. See below
$data=array (“Syam”=>array(“age”=>30,”location”=>”India”),
“Bob”=>array(“age”=>50,”location”=>”USA”) );

Here is a sample program of array in PHP ( using the above array )

<?php
$data=array ("Syam"=>array("age"=>30,"location"=>"India"),"Bob"=>array("age"=>50,"location"=>"USA")  );
echo $data["Bob"]["location"];
?>

Its output will be ;
USA

Adding line break using PHP

For the formatting purpose we need to add line breaks in our output or strings to store in MySQL tables and all. Here I am describing about various methods to add line break using PHP.

In HTML we can add a line break using <br> or <br /> tag.
For this purpose in PHP we need to simply echo that tag like following code

<?php
echo "syam is here<br>for teaching you PHP";
?>

Its output will be
syam is here
for teaching you PHP
( We can see that a line break is added after “syam is here”)

But in several other cases line break is applying using “n” or “rn”, like data storage in csv , txt files or mysql tables or data in a text area etc. In that cases we need to use function nl2br()
to convert the “n” into “<br>” tags to display line break.

See the sample PHP program for display line break using nl2br()

<?php
echo nl2br("syam is herenfor teaching you PHP");
?>

Its output also will be same as our previous PHP program
syam is here
for teaching you PHP
( we can see that “n” is decoded to <br> tag by nl2br() )

There is PHP_EOL constant available instead of using “n: or “rn”.

See the following sample PHP program with constant PHP_EOL

<?php
echo nl2br("syam is here".PHP_EOL."for teaching you PHP");
?>

Its output also will be same as our previous PHP programs
syam is here
for teaching you PHP
( here we can see that constant PHP_EOL is converted into line break using nl2br )

Most of the time we can use “<br>” tag itself for displaying the line breaks in our HTML contents or displaying areas. The other things will come under some advanced cases that we can understand in our later postings.

PHP continue statement

PHP “continue” statement is used within the loops to skip the current loop iteration and goes to the next iteration.

See the syntax structure of “continue statement”

while ( expression 1)
{
if ( expression 2 )
{
continue ;
}
// Operation Statements
}

In this structure if expression 2 return TRUE , continue statement will execute and it will skip that iteration and wont execute the rest portions of code after the “continue” command, control will go to the next iteration in while loop with expression 1.

See the sample PHP program with “continue” statement

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 continue;
 }
 echo $a*$b." ";
}
echo "<br>";
}
?>

Output of this program will be
1 2 4 5
2 4 8 10
3 6 12 15

We can see that it skipped the third records in each loop.

We can use optional parameter with continue statement for specifying how many levels of loops ( not iteration ) should be skipped.

See the following continue syntax structure

while ( expression 1)
{
while ( expression 2 )
{
if ( expression 3 )
{
continue 2;
}
// Operation Statements
}
}

In this structure , if expression 3 becomes TRUE , continue statement will execute with parameter 2. So it will skip the current iteration in while loop with expression 2 also with current iteration with first while loop with expression 1. Next iteration will start from the first while loop.

See the sample php program with continue statement with parameter

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 continue 2;
 }
 echo $a*$b." ";
}
echo "<br>";
}
?>

Output of this program will be
1 2 2 4 3 6

Here we can see that when $b == 3 , control goes to the first while loop with next iteration. Due to the skipping of rest codes line break statement ( echo “<br>”; ) also wont execute.

Note : Difference between Continue and break statement is that

  • Break statement skip the current loop and control will come out from the current loop structure
  • Continue statement skip the current iteration only, control will goes to the next loop iteration

Do a check the programs with break statement in PHP

foreach array in PHP programming

foreach statement is used for making loop over array in loop. It will work only with arrays, and will make errors if we try it with other data types.

foreach statement can be used in two ways.. See the following two structures of foreach loop in PHP

foreach (array as $value)
{
// Operation statement
}

foreach (array as $key => $value)
{
// Operation statement
}

Difference between these two syntax are

  • In the first “foreach” statement , value of each array’s element will be assigned to the variable $value
  • In the second “foreach” statement, key of each array’s element will be assigned to the variable $key

See the sample PHP programs with foreach array loop structure

<?php
$arr = array(10, 20, 30, 40);
foreach ($arr as $value) {
    echo $value." ";
}
?>

Its output will be the values of each elements in array :
10 20 30 40

<?php
$arr = array(10, 20, 30, 40);
foreach ($arr as $key => $value) {
    echo $key." ";
}
?>

Its output will be the key vof each elements in array :
0 1 2 3

When “foreach statement” execute internal pointer will initialize to the first record of array and we don’t need to rest the arrays before the “foreach loop operation”

for in PHP loop programming

for statement is also used to make looping in PHP programming. Its structure is bit more complex than the other loop statements like “while”.

Its structure will look like

for ( expression 1 ; expression 2 ; expression 3 )
{
// Operation statements
}

In “for statement”

  • expression 1 will evaluate before the beginning of loop
  • expression 2 will evaluate before the beginning of each iteration
  • expression 3 will evaluate at the end of each iteration

See the sample program with for statement in PHP

<?php
for ($i=0 ; $i < 10 ; $i++)
{
echo $i." ";
}
?>

Its output will be
0 1 2 3 4 5 6 7 8 9

In this example the first expression ($i=0) will execute before the “for loop”.
Then it will execute the second expression ($i < 10) before each iteration.
At the end of each iteration third expression ($i++) will execute.

The expressions with “for statement” can be empty.
See this PHP program will give the same output like the previous example

<?php
$i=0;
for ( ; $i < 10 ; $i++)
{
echo $i." ";
}
?>

Its output will be :
0 1 2 3 4 5 6 7 8 9

And we can see that the first expression is empty in “for statement”.

PHP do while loop

“do while” loop is almost similar to “while” loop in PHP. The expression with “do while” statement will be executed only at the end of each iteration. So at the first iteration the code will execute before checking the expression. So in the do while loop the first iteration will surely executed .

This is the structure of a PHP do while loop

do
{
// Operation Statements
} while (expression);

See the sample PHP program with “do while” statement

<?php
$a = 0;
do
{
echo $a." ";
$a++;
}while ($a < 3);
?>

Its output will be
0 1 2

while loop in PHP

while statement is using for making a loop in PHP. The while loop will execute as long as the expression with while statement is TRUE. The loop will terminate when the expression return FALSE.

Its structure will be

while ( expression )
{
// Operation statements
}

We can use nested while structures also like
while ( expression 1 )
{
while ( expression 2 )
{
// Operation Statements
}
}

See the sample PHP programs with while statements

<?php
$x=0;
while ( $x < 3)
 {
  echo $x." ";
 $x = $x +1;
 }
?>

It will output the result
0 1 2

See the sample PHP programs with nested while statements

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 3)
{
 $b++;
 echo $a*$b." ";
}
echo "";
}
?>

It will output the result
1 2 3
2 4 6
3 6 9

Break in PHP

“break” statement is using for end the current execution of loop control structure.
Its applicable for for, foreach, while, do-while or switch control structures.

We can add optional parameter with break statement to specify how many control structure should end. By default its value will be 1. Means if we specify break; the it will treat as break 1;

If we specify break 2; it will ends the execution of two control structure .

Look the following structure
while (expression 1)
{
while (expression 2 )
{
break;
}
}
In this structure break statement will ends the execution of while loop with expression 2.

while (expression 1)
{
while (expression 2 )
{
break 2;
}
}
In this structure break statement will ends the execution of two while loop swith expression 1 and expression 2.

See the following sample PHP programs with break statement

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 break 1;
 }
 echo $a*$b." ";
}
echo "";
}
?>

Its output will be :
1 2
2 4
3 6
( when the value of $b = 3 break statement will ends the execution of while ( $b < 5) )

<?php
$a = 0;
while ( $a < 3)
{
$a++;
$b = 0;
while ( $b < 5)
{
 $b++;
 if ($b==3)
 {
 break 2;
 }
 echo $a*$b." ";
}
echo "";
}
?>

Its output will be :
1 2
( when the value of $b = 3 break statement will ends the execution of two while loops)

break statement is really useful when we want to terminate a loop control structure or a switch case in a particular condition. In some scenarios we need to search for something inside another thing in a loop. we can use break statement when we got the desired result and can eliminate the rest unwanted execution of loops.

Share
Share