You are on page 1of 23

PHP Programming

Unit III
SWITCH STATEMENT
The switch statement is used to perform different actions based on different
conditions.
The PHP switch Statement
Use the switch statement to select one of many blocks of code to be
executed.
Syntax:
switch (expression)
{
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
}

This is how it works:


The expression is evaluated once
The value of the expression is compared with the values of each case

1
If there is a match, the associated block of code is executed
The break keyword breaks out of the switch block
The default code block is executed if there is no match.

Example Program
$favcolor = "red";
switch ($favcolor)
{
case "red":

2
echo "Your favorite color is red!";
break;
case "blue":
"Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}

Output
Your favorite color is red!

LOOPS IN PHP
Loops are used to execute the same block of code again and again, as long as a
certain condition is true.
In PHP, we have the following loop types:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as
long as the specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array

3
USING THE WHILE() LOOP
The PHP while Loop
The while loop executes a block of code as long as the specified condition is
true.

Syntax
while(condition)
{
//code to be executed
}

Flow Chart

Example Program 1:
<?php
// Declare a number
$num = 10;
4
// While Loop
while ($num < 20)
{
echo $num "\n";
$num += 2;
}
?>

Output
10
12
14
16
18

Example Program 2:
<?php
$n=1;
while($n<=5)
{
echo $n "\n";
$n++;
}
?>
Output
1
2

5
3
4
5
USING THE FOR() LOOP
The for loop is used when the user knows how many times the block needs to
be executed. The for loop contains the initialization expression, test condition, and
update expression (expression for increment or decrement).
Syntax:
for (initialization expression; test condition; update expression)

// Code to be executed

Flowchart of for Loop:

6
Example Program:

<?php

$number=5;
for($i=1;$i<=10;$i++)
{

$result=$number*$i;
echo"$number*$i=$result";
echo"<br>";
}

?>

Output

5*1=5

5*2=10

5*3=15
5*4=20

5*5=25

5*6=30

5*7=35

5*8=40

5*9=45

5*10=50

7
Example Program 2:
<?php
// for Loop to display numbers
for( $num = 0; $num < 20; $num += 5)
{
echo $num . "\n";
}
?>

Output
0
5
10
15

PHP FUNCTIONS
A function is a block of code written in a program to perform some specific
task. They take informations as parameter, executes a block of statements or perform
operations on this parameters and returns the result.
PHP provides us with two major types of functions:
Built-in functions
PHP provides us with huge collection of built-in library functions. These
functions are already coded and stored in form of functions. To use those we just
need to call them as per our requirement like, var_dump, fopen(), print_r(), gettype()
and so on.

8
User Defined Functions
Apart from the built-in functions, PHP allows us to create our own customised
functions called the user-defined functions. Using this we can create our own
packages of code and use it wherever necessary by simply calling it.

Why should we use functions?


Reusability
If we have a common code that we would like to use at various parts of a
program, we can simply contain it within a function and call it whenever required.
Easier error detection
Since, our code is divided into functions, we can easily detect in which
function, the error could lie and fix them fast and easily.
Easily maintained
If any line of code needs to be changed, we can easily change it inside the
function and the change will be reflected everywhere, where the function is called.
Hence, easy to maintain.

Syntax:
function function_name()
{
executable code;
}

Example Program
<?php
function sayHello()
{

9
echo "Hello PHP Function";
}
sayHello(); //calling function
?>

Output:
Hello PHP Function

PHP Functions - Returning values


To let a function return a value, use the return statement:
Example
function sum($x, $y)
{
$z = $x + $y;
return $z;
}
echo "5 + 10 = " . sum(5, 10) "<br>";
echo "7 + 13 = " . sum(7, 13) "<br>";
echo "2 + 4 = " . sum(2, 4);
Output
5 + 10 = 15
7 + 13 = 20
2+4=6

Parameter passing to Functions


PHP allows us two ways in which an argument can be passed into a function:

10
Pass by Value
On passing arguments using pass by value, the value of the argument gets
changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.
Pass by Reference
On passing arguments as pass by reference, the original value is passed.
Therefore, the original value gets altered. In pass by reference we actually pass the
address of the value, where it is stored using ampersand sign(&)
Example Program
<?php
// pass by value
function valGeek($num)
{
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num)
{
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n \n";

11
refGeek($n);
echo "The original value changes to $n";
?>

Output
The original value is still 10
The original value changes to 20

CREATING AN ARRAY
Arrays in PHP is a type of data structure that allows us to store multiple
elements of similar data type under a single variable thereby saving us the
effort of creating a different variable for every data.
The arrays are helpful to create a list of elements of similar types, which can
be accessed using their index or key.
There are basically three types of arrays in PHP:
1. Indexed or Numeric Arrays
2. Associative Arrays
3. Multidimensional Arrays

1. Indexed or Numeric Arrays


These type of arrays can be used to store any type of elements, but an index is
always a number.
By default, the index starts at zero.
These arrays can be created in two different ways as shown in the following
example.

12
Example Program:
<?php
// One way to create an indexed array
$name_one = array("Zack", "Anthony", "Ram", "Salim", "Raghav");
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
// Second way to create an indexed array
$name_two[0] = "ZACK";
$name_two[1] = "ANTHONY";
$name_two[2] = "RAM";
$name_two[3] = "SALIM";
$name_two[4] = "RAGHAV";
// Accessing the elements directly
echo "Accessing the 2nd array elements directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>

Output
Accessing the 1st array elements directly:
Ram
Zack
Raghav

13
Accessing the 2nd array elements directly:
RAM
ZACK
RAGHAV

Associative Arrays
These types of arrays are similar to the indexed arrays but instead of linear
storage, every value can be assigned with a user-defined key of string type.
Example Program
<?php
// Define an associative array
$student = array(
'name' => 'John',
'age' => 20,
'grade' => 'A'
);
// Accessing elements in the associative array
echo 'Name: ' . $student['name'] . '<br>';
echo 'Age: ' . $student['age'] . '<br>';
echo 'Grade: ' . $student['grade'] . '<br>';
?>

Output
Name: John
Age: 20
Grade: A

14
3.Multidimensional Arrays
A multidimensional array in PHP is an array that contains one or more arrays
as its elements. These arrays can be indexed or associative arrays. Multidimensional
arrays are useful when you need to organize data in a more complex structure.
Example Program
<?php
// Define a multidimensional array
$students = array(
array(
'name' => 'John',
'age' => 20,
'grade' => 'A'
),
array(
'name' => 'Alice',
'age' => 22,
'grade' => 'B'
),
array(
'name' => 'Bob',
'age' => 21,
'grade' => 'C'
)
);
// Accessing elements in the multidimensional array
echo 'Name: ' . $students[0]['name'] . ', Age: ' . $students[0]['age'] . ', Grade: ' .
$students[0]['grade'] . '<br>';

15
echo 'Name: ' . $students[1]['name'] . ', Age: ' . $students[1]['age'] . ', Grade: ' .
$students[1]['grade'] . '<br>';
echo 'Name: ' . $students[2]['name'] . ', Age: ' . $students[2]['age'] . ', Grade: ' .
$students[2]['grade'] . '<br>';
?>
Output
Name: John, Age: 20, Grade: A
Name: Alice, Age: 22, Grade: B
Name: Bob, Age: 21, Grade: C

MODIFYING ARRAY ELEMENTS


Modifying array elements in PHP refers to the process of changing the values
of individual elements within an array using their respective keys.
Example:
<?php
// Define an associative array
$fruits = array(
'apple' => 'red',
'banana' => 'yellow',
'grape' => 'purple'
);
// Display the original array
echo "Original Array:<br>";
print_r($fruits);
// Modify the value of the 'banana' key
$fruits['banana'] = 'green';
// Modify the value of the 'grape' key

16
$fruits['grape'] = 'green';
// Display the modified array
echo "<br>Modified Array:<br>";
print_r($fruits);
?>
Output
Original Array:
Array
(
[apple] => red
[banana] => yellow
[grape] => purple
)
Modified Array:
Array
(
[apple] => red
[banana] => green
[grape] => green
)

PROCESSING ARRAYS WITH LOOPS


Processing arrays with loops is a common operation in PHP, allowing you to
iterate through each element of an array and perform actions on them. Here's an
example using a for loop to process an array and display its elements.

17
Example Program
<?php
// Define an indexed array
$numbers = array(1, 2, 3, 4, 5);
// Using a for loop to process the array
echo "Using a for loop:<br>";
$count = count($numbers);
for ($i = 0; $i < $count; $i++)
{
echo "Element at index $i: $numbers[$i]<br>";
}
?>

In this example, we have an indexed array called $numbers with elements 1, 2,


3, 4, and 5. The for loop iterates through each element of the array and displays the
index and value of each element.

Output
Using a for loop:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5

18
GROUPING FORM SELECTIONS WITH ARRAYS
Grouping form selections with arrays in PHP is a common technique when
dealing with HTML forms that have multiple options.
This involves using arrays as the names of form elements to organize related
data.
Example Program
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Grouping Form Selections with Arrays</title>
</head>
<body>
<form method="post" action="process_form.php">
<label for="fruit">Select a fruit:</label>
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="orange">Orange</option>
</select>
<br><br>
<label for="color">Select a color:</label>
<select name="color">
<option value="red">Red</option>
<option value="yellow">Yellow</option>
<option value="orange">Orange</option>

19
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

In this HTML form, there are two dropdowns (<select> elements) with the
names "fruit" and "color". The options within each dropdown represent different
fruits and colors, respectively.

Output: process_form.php
Now, let's create a PHP script (process_form.php) to process the form submissions:
<?php
// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// Retrieve the selected fruit and color from the form
$selectedFruit = $_POST['fruit'];
$selectedColor = $_POST['color'];
// Display the selected options
echo "You selected: <br>";
echo "Fruit: $selectedFruit<br>";
echo "Color: $selectedColor<br>";
}
else
{

20
// If the form is not submitted, display a message
echo "Please submit the form.";
}
?>

Understanding the Output:


Initial Form Display
When you load the HTML form, you see dropdowns for selecting a fruit and a
color.
Form Submission
After selecting options and submitting the form, the process_form.php script
processes the form data.
Processed Output
The processed output displays the selected fruit and color.

For example, if you select "Banana" and "Yellow", the output will be:
Output
You selected:
Fruit: banana
Color: yellow

USING ARRAY FUNCTIONS


PHP Arrays are a data structure that stores multiple elements of a similar type
in a single variable.
The arrays are helpful to create a list of elements of similar type. It can be
accessed using their index number or key.
The array functions are allowed to interact and manipulate the array elements

21
in various ways.
The PHP array functions are used for single and multi-dimensional arrays.
Example
PHP program to sort an array in ascending order using sort() function and print
the sorted array.
<?php
// Create an array object
$arr = array(1, 4, 3, 2, 6);
// Sort function to sort array elements
sort($arr);
// Prints the sorted array
print_r($arr);
?>

Output
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 6
)
S.No PHP Array Functions Description
1 array_chunk()
Split an array into parts or chunks of a
given size.

22
2 array_combine()
Create a new array by using one array
for keys and another array for values.

3 array_count_values() Count all the values inside an array

4 array_fill() Fill an array with values.

5 array_filter() Filter the elements of an array using a user-


defined function
6 array_flip()
Exchange elements within an array

7 array_intersect_assoc() Compute the intersection of two or more


arrays.
8 array_intersect() Compare the values of two or more arrays
and returns the matches.
9 array_push() Push new elements into an array.

10 array_pop()
Delete or pop out and return the last
element from an array passed to it as a
parameter.

23

You might also like