Faculty of Computer Applications &
Information Technology
BCA
210301501 WEBSITE DEVELOPMENT USING
PHP & MySQL
Unit 2
Conditional Statement, Looping, PHP Functions
And Arrays
Conditional Statements
● In PHP we have the following conditional statements:
● if statement - executes some code if one condition is true
● if...else statement - executes some code if a condition is true and
another code if that condition is false
● if...elseif....else statement - executes different codes for more than two
conditions
● switch statement - selects one of many blocks of code to be executed
Faculty of Computer Applications & IT
The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
<?php
$t = 10;
if ($t < "20") {
echo "Have a good day!";
} Faculty of Computer Applications & IT
The if.. else Statement
The if....else statement executes some code if a condition is true and
another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Faculty of Computer Applications & IT
The if.. else Statement
<?php
$t = 10;
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Faculty of Computer Applications & IT
The if.. elseif …. Else Statement
The if....elseif...else statement executes different codes for more than two
conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
} Faculty of Computer Applications & IT
The if.. elseif …. Else Statement
<?php
$t = 10;
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?> Faculty of Computer Applications & IT
The switch Statement
The switch statement is used to perform different actions based on
different conditions.
Use the switch statement to select one of many blocks of code to be
executed.
Faculty of Computer Applications & IT
The switch Statement
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
} Faculty of Computer Applications & IT
The switch Statement
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "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!";
}
?> Faculty of Computer Applications & IT
Points for switch case
● The default is an optional statement. Even it is not important, that
default must always be the last statement.
● There can be only one default in a switch statement. More than one
default may lead to a Fatal error.
● Each case can have a break statement, which is used to terminate the
sequence of statement.
● The break statement is optional to use in switch. If break is not used,
all the statements will execute after finding matched case value.
● PHP allows you to use number, character, string, as well as functions
in switch expression.
● Nesting of switch statements is allowed, but it makes the program
more complex and less readable.
● You can use semicolon (;) instead of colon (:). It will not generate any
error.
Faculty of Computer Applications & IT
Loops
● PHP while loops execute a block of code while the specified condition
is true.
● In PHP, we have the following looping statements:
● 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
Faculty of Computer Applications & IT
The While Loops
The while loop executes a block of code as long as the specified
condition is true.
Syntax
while (condition is true) {
code to be executed;
<?php
$x = 1;
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
} Faculty of Computer Applications & IT
The do…While Loops
The do...while loop will always execute the block of code once, it will
then check the condition, and repeat the loop while the specified
condition is true.
Syntax
do {
code to be executed;
} while (condition is true);
Faculty of Computer Applications & IT
The do…While Loops
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Faculty of Computer Applications & IT
The for Loop
PHP for loops execute a block of code a specified number of times.
The for loop is used when you know in advance how many times the
script should run.
Syntax
for (init counter; test counter; increment counter) {
code to be executed;
}
Faculty of Computer Applications & IT
The for Loop
<?php
for ($x = 0; $x <= 10; $x++) {
echo "The number is: $x <br>";
}
?>
Faculty of Computer Applications & IT
The for each Loop
The foreach loop works only on arrays, and is used to loop through
each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be executed;
}
For every loop iteration, the value of the current array element is
assigned to $value and the array pointer is moved by one, until it
reaches the last array element.
Faculty of Computer Applications & IT
The for each Loop
<?php
$colors = array("red", "green", "blue", "yellow");
foreach ($colors as $value)
{
echo "$value <br>";
}
?>
Faculty of Computer Applications & IT
Variable Scope in PHP
In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can
be referenced/used.
PHP has three different variable scopes:
● local
● global
● static
Faculty of Computer Applications & IT
Global Variable
A variable declared outside a function has a GLOBAL SCOPE and can
only be accessed outside a function
Faculty of Computer Applications & IT
Global Variable
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
echo "<p>Variable x outside function is: $x</p>";
?> Faculty of Computer Applications & IT
Local Variable
A variable declared within a function has a LOCAL SCOPE and can
only be accessed within that function:
Faculty of Computer Applications & IT
Local Variable
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?> Faculty of Computer Applications & IT
Local Variable
You can have local variables with the same name in different
functions, because local variables are only recognized by the function
in which they are declared.
Faculty of Computer Applications & IT
PHP The Global Keyword
The global keyword is used to access a global variable from within a
function.
To do this, use the global keyword before the variables (inside the
function):
Faculty of Computer Applications & IT
PHP The Global Keyword
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?> Faculty of Computer Applications & IT
PHP The Global Keyword
PHP also stores all global variables in an array called
$GLOBALS[index].
The index holds the name of the variable.
This array is also accessible from within functions and can be used to
update global variables directly.
Faculty of Computer Applications & IT
PHP The static Keyword
Normally, when a function is completed/executed, all of its variables
are deleted.
However, sometimes we want a local variable NOT to be deleted. We
need it for a further job.
To do this, use the static keyword when you first declare the variable
Faculty of Computer Applications & IT
PHP The static Keyword
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the
information it contained from the last time the function was called.
Note: The variable is still local to the function.
Faculty of Computer Applications & IT
What is PHP Function
● A function is a block of statements that can be used repeatedly in a
program.
● A function will not execute immediately when a page loads.
● A function will be executed by a call to the function.
Faculty of Computer Applications & IT
Creating User defined Function
function functionName() {
code to be executed;
}
A function name can start with a letter or underscore (not a
number).
Function names are NOT case-sensitive.
Faculty of Computer Applications & IT
Creating User defined Function
<?php
function Msg() {
echo "Hello world!";
Msg(); // call the function
?>
Faculty of Computer Applications & IT
Function with one Argument
● Information can be passed to functions through arguments.
● An argument is just like a variable.
● Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
Faculty of Computer Applications & IT
Function with one Argument
<?php
function Name($fname) {
echo $fname.” <br>";
}
Name("Kohli");
Name("Dhoni");
Name("Chahal");
Name("Rohit");
Name("Hardik");
?>
Faculty of Computer Applications & IT
Function with two Argument
<?php
function Name($fname, $team) {
echo $fname . $team “<br>";
}
Name("Dhoni", "India");
Name("Buttler", "England");
Name("Warner", "Australia");
?>
Faculty of Computer Applications & IT
Default Argument
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(150);
setHeight(); // will use the default value of 50
setHeight(125);
setHeight(180);
?>
Faculty of Computer Applications & IT
Return Value
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}
echo "2 + 10 = " . sum(2, 10) . "<br>";
echo "7 + 5 = " . sum(7, 5) . "<br>";
echo "2 + 3 = " . sum(2, 3);
?>
Faculty of Computer Applications & IT
Arrays in PHP
● An array is a data structure that stores one or more similar type of values in a
single value.
● For example if you want to store 100 numbers then instead of defining 100
variables its easy to define an array of 100 length.
● There are three different kind of arrays and each array value is accessed using
an ID which is called array index.
Faculty of Computer Applications & IT
Arrays in PHP
Numeric array - An array with a numeric index. Values are stored and accessed
in linear fashion.
Associative array - An array with strings as index. This stores element values
in association with key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values
are accessed using multiple indices.
Faculty of Computer Applications & IT
Arrays in PHP
● An array is a collection of data values.
● Array is organized as an ordered collection of key-value pairs.
● An array is a special variable, which can store multiple values in one single
variable.
● An array can hold all your variable values under a single name and you can
access the values by referring to the array name.
● Each element in the array has its own index so that it can be easily accessed.
Faculty of Computer Applications & IT
What is Array?
An array is a special variable, which can hold more than one value at a time.
• If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";
In PHP, the array() function is used to create an
array: array()
Faculty of Computer Applications & IT
PHP Indexed Arrays
There are two ways to create indexed arrays:
• The index can be assigned automatically (index always starts at 0), like this:
Initializing indexed array
• $cars = array("Volvo", "BMW", "Toyota");
or
The index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Print_r($cars) - used to print array and used for testing purpose
Faculty of Computer Applications & IT
Adding value to the end of an Array
Adding value to the end of an array
<?php
$colors=array("red",24,"blue",33.66);
echo "<ul>";
$colors[]="pink";
for($i=0;$i<=4;$i++)
echo "<li>$colors[$i] </li>";
echo "</ul>";
?>
Faculty of Computer Applications & IT
Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
• There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
Or
key=Value
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Faculty of Computer Applications & IT
For each Loop
For each loop
Syntax: foreach($array as $value)
PHP executes the body of the loop once for each element of $array,
with $value set to the current elements.
Elements are processed by their internal order
Faculty of Computer Applications & IT
Storing data in Array
Storing data in array
• To store the data in array, the array should be defined before. But if it is
not defined , then it is created automatically.
• Trying to access the members of array which does not exist is not
allowed.
• Simple assignment to initialize an array
• Indexed array:
$a[0]=10;
$a[1]=20;
$a[2]=30;
• For Associative array:
$a[‘one’]=1;
$a[‘two’]=2;
$a[‘three’]=3;
Faculty of Computer Applications & IT
Storing data in Array
Adding values to the end of array
• To insert more values at the end of array use[]
syntax.
E.g
• Indexed array:
$A=array(1,2,3);
$A[]=4;
-adds value at the end ofthe array it gets the numeric index 3.
• Associative array:
$A=array(‘one’=>1, ’two’=>2, ’three’=>3);
$A[]=4;
- adds value at the end of the array
Faculty but it gets
of Computer the numeric
Applications & IT index 0
Assigning a Range of Values
The range() function creates an array of consecutive integer or character between
two values we pass to it as a parameter.
• $number=range(2,5) /*output
print_r($number)
/*output
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 5
)*/
• $letter=range(‘a’, ’d’);
/*output
Array
(
[0] => a
[1] => b
[2] => c
Faculty of Computer Applications & IT
Getting the size of an Array
The count() functions are used to return number of elements in the array.
Syntax: count($array );
$a= array(1,2,3,4);
$size=count($a); //count 4
• The sizeof() function is an alias of the count() function.
$a= array(1,2,3,4);
$size=sizeof($a); //size 4
Faculty of Computer Applications & IT
Multidimensional Array in PHP
A multidimensional array in PHP is an array that contains one or more arrays as its
elements. This is useful for storing data in a table-like structure such as rows and
columns.
Faculty of Computer Applications & IT
Multidimensional Array in PHP
Two-dimensional Indexed Array
numeric keys for both dimensions.
$students = array(array("John", 20, "A"),array("Alice", 22, "B"),array("Mark", 19, "A+"));
Jhon 20 A
Alice 22 B
Mark 19 A+
echo $studentDetails["student1"]["name"]; // Output: John
Faculty of Computer Applications & IT
Multidimensional Array in PHP
Outer array with names or IDs, and inner array with key-value pairs.
$studentDetails = array( "student1" => array("name" => "John", "age" => 20, "grade" =>"A"),
"student2" => array("name" => "Alen","age" => 22,"grade" => "B"));
echo $studentDetails["student1"]["name"]; // Output: John
$studentDetails student1 Name: Jhon
Age : 20
Grade:A
Student2 Name: Alen
Age : 22
Grade : B
Faculty of Computer Applications & IT
Multidimensional Array in PHP
Mixed (Indexed + Associative)
You can combine both indexed and associative styles.
$data = array(array( "name" => "John", "age" => 20 ),
array("name" => "Alice","age" => 22 ));
echo $data[1]["name"]; // Output: Alice
Name=Jhon
Index= 0
Age=20
$data
Name= alice
Index= 1
Age= 22
Faculty of Computer Applications & IT
Looping through Multidimensional Arrays
Using foreach:
foreach ($studentDetails as $student)
{
foreach ($student as $key => $value)
{
echo "$key: $value<br>";
}
echo "<hr>";
}
Faculty of Computer Applications & IT
PHP Sort Function for Arrays
● sort()
● rsort()
● asort()
● arsort()
● ksort()
● krsort()
Faculty of Computer Applications & IT
PHP Sort Function for Arrays
● sort() - sort arrays in ascending order
● rsort() - sort arrays in descending order
● asort() - sort associative arrays in ascending order, according to the value
● arsort() - sort associative arrays in descending order, according to the value
● ksort() - sort associative arrays in ascending order, according to the key
● krsort() - sort associative arrays in descending order, according to the key
Faculty of Computer Applications & IT
Other Function
● array_change_key_case()
● array_flip()
● array_keys()
● array_merge()
● array_pop()
● array_push()
● array_rand()
● array_shift()
● array_values()
Faculty of Computer Applications & IT
array_change_key_case() function
● PHP array_change_key_case() function changes the case of all key of an array.
● Note: It changes case of key only.
Syntax:
array_change_key_case(array,case);
● Parameters
● arr − The array. Required.
● case − Specify the case. The default is Lowercase i.e. CASE_LOWER.
Optional.
● Example:
● $salary=array("Sonu"=>"550000","Vimal"=>"250000","Ratan"=>"200000");
Faculty of Computer Applications & IT
array_flip() function
● The array_flip() function flips/exchanges all keys with their associated values in
an array.
Syntax:
array_flip($arr)
● Example:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?> Faculty of Computer Applications & IT
array_keys() function
● Just like values, we can also extract just the keys from an array.
Syntax:
array_keys($arr)
● Example:
<?php
$a=array("Volvo"=>"XC90","BMW"=>"X5","Toyota"=>"Highlander");
print_r(array_keys($a));
?>
Faculty of Computer Applications & IT
array_merge() function
● The array_merge() function merges one or more arrays into one array.
Syntax
array_merge(array1,array2,array3...)
● Example:
<?php
$a1=array("a"=>"red","b"=>"green");
$a2=array("c"=>"blue","b"=>"yellow");
print_r(array_merge($a1,$a2));
?>
Faculty of Computer Applications & IT
array_pop() function
● The array_pop() function deletes the last element of an array.
Syntax
array_pop(array)
● Example
<?php
$a=array("red","green","blue");
array_pop($a);
print_r($a);
?>
Faculty of Computer Applications & IT
array_push() function
● The array_push() function inserts one or more elements to the end of an array.
Syntax
array_push(array,value1,value2...)
● Example:
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
Faculty of Computer Applications & IT
array_rand() function
● The array_rand() function returns a random key from an array, or it returns an
array of random keys if you specify that the function should return more than
one key.
Syntax
array_rand(array,number)
● Example:
<?php
$colors = array("red", "black", "blue", "green", "white", "yellow");
echo "Color of the day: ". $colors[array_rand($colors)];
?> Faculty of Computer Applications & IT
array_shift() function
● The array_shift() function removes the first element from an array, and returns
the value of the removed element.
● Note: If the keys are numeric, all elements will get new keys, starting from 0 and
increases by 1.
Syntax
array_shift(array)
● Example:
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_shift($a); Faculty of Computer Applications & IT
array_values() function
● The array_values() function returns an array containing all the values of an
array.
Syntax
array_values(array)
● Example:
<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>
Faculty of Computer Applications & IT
Adding Elements
Array Functions
Adding Elements
array_push($arr, "newElement"); // Add to end
array_unshift($arr, "start"); // Add to beginning
Removing Elements
array_pop($arr); // Removes last element
array_shift($arr); // Removes first element
unset($arr[2]); // Removes element at index 2
Faculty of Computer Applications & IT
Array Functions
Searching in Arrays
in_array("value", $arr); // True if found
array_search("value", $arr); // Returns index
Counting and Size
count($arr); // Total number of elements
Faculty of Computer Applications & IT
Array Functions
Slicing and Chunking
array_slice(array $array, int $offset, int $length)
$array = Input array
$offset = starting index (0 based) , Negative values start from end
$length = number of elements to return if not set then returns full length
array_slice($arr, 2, 3); // Get sub-array from index 2, 3 items
Reversing Arrays
array_reverse($arr);
Faculty of Computer Applications & IT
print_r() function
● The print_r() function is used to print human-readable information about a
variable.
Syntax
print_r(var_name, return_output)
Faculty of Computer Applications & IT
print_r() function
Faculty of Computer Applications & IT
Hash Table
● Hash Table is a data structure which stores data in an associative manner.
● In a hash table, data is stored in an array format, where each data value has its
own unique index value.
● Access of data becomes very fast if we know the index of the desired data.
● Thus, it becomes a data structure in which insertion and search operations are
very fast irrespective of the size of the data.
● Hash Table uses an array as a storage medium and uses hash technique to
generate an index where an element is to be inserted or is to be located from.
Faculty of Computer Applications & IT
Hash Table
● Hashing is a technique to convert a range of key values into a range of indexes
of an array.
Faculty of Computer Applications & IT
Function with Arguments in PHP
Three functions are used when arguments are passed in PHP.
● func_get_arg
● func_get_args
● func_num_args()
Faculty of Computer Applications & IT
func_get_arg()
● func_get_arg() is used to retrieve a single argument from the list of arguments
passed to a user-defined function.
● It allows the programmer to easily create functions that accept variable-length
argument lists.
● The argument retrieved is the argument present at the offset specified by
argument_number .
● The argument list starts at 0.
● If the argument specified by argument_number doesn't exist, a warning is
generated.
Faculty of Computer Applications & IT
func_num_args()
● func_num_args() returns the number of arguments that have been passed to a
user-defined function.
● It's most often used in conjunction with func_get_arg() and func_get_args() to
ensure that the right number of arguments have been passed to a function.
Faculty of Computer Applications & IT
func_get_args()
● func_get_args() returns an array containing the list of arguments passed to a
user-defined function.
● Like func_get_arg() , this function allows the programmer to easily create
functions that accept variable-length argument lists.
● Unlike most functions, func_get_args() cannot always be used as an argument
for some functions. It's better to assign the output of func_get_args() to a
variable and then use the variable as the argument for a function.
Faculty of Computer Applications & IT