1
III BCA PHP & MySQL UNIT 2
Programming with PHP: Conditional statements: if, if-else, switch, The? Operator, looping statements:
while Loop, do-while Loop, for Loop
Arrays in PHP: Introduction- What is Array? Creating Arrays, Accessing Array elements, Types of Arrays:
Indexed v/s Associative arrays, Multidimensional arrays, Creating Array, Accessing Array, Manipulating
Arrays, displaying array, Using Array Functions, Including and Requiring Files- use of Include () and Require
(), Implicit and Explicit Casting in PHP
Conditional statements:
Conditional statements in PHP are a way to control the flow of a program based on certain conditions.
The condition is a Boolean expression that evaluates to either true or false.
In PHP we have the following
if Statement
if .. else Statement
if...elseif .. else Statement
Nested if statement
switch Statement
if Statement
The if statement executes the block of code only if the condition evaluates to true.
If statement is used to executes the block of code exist inside the if statement only if the specified
condition is true
Syntax:
if (condition) {
// code to execute if condition is true
}
Example
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
|Dept of Computer Science JSS College for Women Chamarajanagar|
2
III BCA PHP & MySQL UNIT 2
if...else Statement
Checks the condition. If true, if block runs. If false, the else block runs.
Syntax:
if (condition) {
// code if condition is true
} else {
// code if condition is false
}
Example
<?php
$a=10;
$b=20;
if($a>$b) {
echo "a is greater than b";
}
else {
echo "b is greater than a";
}
?>
if...elseif...else Statement
This structure is used when you need to check multiple conditions and execute different blocks of
code depending on which condition is true.
PHP evaluates the conditions top to bottom.
As soon as one condition is true, it runs that block and skips the rest.
If no conditions are true, the else block runs.
Syntax:
if (condition1) {
// Code runs if condition1 is true
} elseif (condition2) {
// Code runs if condition2 is true
} elseif (condition3) {
// Code runs if condition3 is true
} else {
// Code runs if none of the above conditions are true
}
|Dept of Computer Science JSS College for Women Chamarajanagar|
3
III BCA PHP & MySQL UNIT 2
Example
<?php
$a=3;
$b=4;
$c=6;
if($a>$b && $a>$c){
echo "A is Biggest Number";
}
else if($b>$c){
echo "B is Biggest Number";
}
else{
echo "C is Biggest Number";
}
?>
Nested if statement
A nested if is an if statement inside another if or else block. It's used when you want to make a decision
based on another condition, but only if a previous condition is true.
Syntax
if (condition1) {
// First-level condition
if (condition2) {
// Runs only if condition1 AND condition2 are true
} else {
// Runs if condition1 is true, but condition2 is false
}
} else {
// Runs if condition1 is false
}
Example
<?php
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
Switch statement
PHP has a built-in multi-way decision statement knows as a switch
|Dept of Computer Science JSS College for Women Chamarajanagar|
4
III BCA PHP & MySQL UNIT 2
The switch statement evaluates the expression once
The value of the expression is compared with the values of each case
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
Syntax
switch (expression) {
case value1:
// code to run if expression == value1
break;
case value2:
// code to run if expression == value2
break;
case value3:
// code to run if expression == value3
break;
default:
// code to run if no cases match
}
Example
<?php
$day = "Wednesday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Wednesday":
echo "Midweek hustle.";
break;
case "Friday":
echo "Almost weekend!";
break;
case "Sunday":
echo "Time to relax.";
break;
default:
echo "Just a regular day.";
}
?>
The?? Operator
The ?? operator in PHP is the null coalescing operator. It allows you to check if a variable is set and
not null. If the variable is null or not set, it provides a default value.
Syntax: $variable = $value?? $default Value;
1. $value: The variable or expression being checked.
|Dept of Computer Science JSS College for Women Chamarajanagar|
5
III BCA PHP & MySQL UNIT 2
2. $default Value: The value that will be assigned if $value is null or not set.
Example
<?php
$userName = null;
$greeting = $userName?? "Guest";
echo $greeting; // Output: Guest
?>
Ternary Operator (the?: Operator) or Conditional Operator
The ternary operator (?:) is a conditional operator used to perform a simple comparison or check on a
condition having simple statements.
Syntax: condition? value_if_true : value_if_false;
1. condition: An expression that evaluates to true or false
2. value_if_true: Returned if the condition is true
3. value_if_false: Returned if the condition is false
Example
<?php
$age = 16;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status;
?>
LOOPING STATEMENTS:
what is Looping?
A looping structure is a sequence of statements executed repeatedly until some condition for
termination of the loop is satisfied. It is also known as iterative statements
There are four main types of loops in PHP:
1. for Loop
2. while Loop
3. do...while Loop
4. foreach Loop
for loop: -
The for loop is used when you know exactly how many times you want the loop to run. It consists
of three parts: initialization, condition, and increment.
OR
loops through a block of code a specified number of times
Syntax;
|Dept of Computer Science JSS College for Women Chamarajanagar|
6
III BCA PHP & MySQL UNIT 2
for (initialization; condition; increment) {
// Code to be executed
}
Initialization: is executed (one time) before the execution of the code block.
condition defines the condition for executing the code block.
increment: is executed (every time) after the code block has been executed.
Example
<?php
for ($i = 1; $i <= 5; $i++) {
echo " $i\n";
}
?>
while Loop
it is entry-controlled looping statement
loops through a block of code as long as the specified condition is true
Syntax:
while (condition) {
// Code to be executed
}
The while loop evaluates the condition inside the parentheses ().
If condition is true, statements inside the body of while loop are executed. Then, condition is
evaluated again. The process goes on until condition is evaluated to false.
If t condition is false, the loop terminates (ends).
Example
<?php
$i = 1;
while ($i <= 5) {
echo " $i";
$i++;
}
?>
do...while Loop
The do...while loop is similar to the while loop, but the code is executed at least once before the
condition is tested. The condition is checked after the loop's body is executed.
It is also called exit controlled looping statement
OR
loops through a block of code once, and then repeats the loop as long as the specified condition is true
|Dept of Computer Science JSS College for Women Chamarajanagar|
7
III BCA PHP & MySQL UNIT 2
Syntax
do {
// Code to be executed
} while (condition);
Example
<?php
$i = 1;
do {
echo " $i";
$i++;
} while ($i <= 5);
?>
foreach statement
loops through a block of code for each element in an array
OR
The foreach loop is used for iterating over arrays or objects. It automatically fetches each value of
an array or object one by one.
Syntax:
foreach ($array as $value) {
// Code to be executed
}
Example
<?php
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $color) {
echo "$color";
}
?>
Nested looping statements
Nested loops are loops inside other loops
Syntax:
for (initialization; condition; increment)
{
for (initialization; condition; increment)
{
// Code to be executed
}
}
Example
<?php
|Dept of Computer Science JSS College for Women Chamarajanagar|
8
III BCA PHP & MySQL UNIT 2
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 2; $j++) {
echo "i = $i, j = $j\n";
}
}
?>
Break statement
In PHP, the break statement is used to exit a loop or switch statement before its normal termination.
When the break statement is encountered, it immediately stops the loop's execution and continues with
the next statement after the loop or switch.
Syntax: break;
Example
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 6) {
break;
}echo " $i";
}
?>
Continue statement
In PHP, the continue statement is used to skip the current iteration of a loop and move to the next
iteration.
Syntax: continue;
Example
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue;
}
echo "$i";
}
?>
ARRAYS IN PHP
What is an Array?
An array is a special variable that can hold many values under a single name, and you can access the
values by referring to an index number or name.
OR
An array in PHP is a special variable that can hold multiple values at once. Instead of creating a separate
variable for each value, you can store a collection of related values in one variable.
Creating Array in PHP
You can create an array in two ways
|Dept of Computer Science JSS College for Women Chamarajanagar|
9
III BCA PHP & MySQL UNIT 2
the array () function
short [] (square brackets)
The array () function:
It is functions used to create arrays.
Syntax: array (value1, value2, value3, ...);
You can use it to create indexed arrays or associative arrays.
Each element in an array is separated by comma.
Example
1. Creating Indexed Array Using array ()
<?php
$a =array (1,2,3);
foreach ($a as $i) {
echo $i ;
}
?>
2. Creating Associative Array Using array ()
<?php
$person = array(
"name" => "Sara",
"age" => 25,
"city" => "Dubai"
);
?>
3. Creating Multidimensional Array Using array ()
<?php
$students = array(
array(1,2),
array(3,4),
array (5,6)
);
?>
short [] (square brackets)
PHP allows you to use square brackets [] as a shortcut for creating arrays instead of using the array()
function.
Syntax: $arrayName = [value1, value2, value3, ...];
Examples of Using [] to Create Arrays
1. Creating Indexed Array
<?php
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[0];
?>
|Dept of Computer Science JSS College for Women Chamarajanagar|
10
III BCA PHP & MySQL UNIT 2
2. Creating Associative Array
<?php
$person = [
"name" => "ABC",
"age" => 28,
"city" => "Blore"
];
echo $person["city"];
?>
3. Creating Multidimensional Array
<?php
$a = [
[1,2,3],
[4,5,6],
[7,8,9]
];
echo $a[1][0];
?>
In PHP, there are three types of arrays:
Indexed arrays - Arrays with a numeric index
Associative arrays - Arrays with named keys
Multidimensional arrays - Arrays containing one or more arrays
Indexed arrays
In indexed arrays each item has an index number.
By default, the first item has index 0, the second item has item 1, etc.
OR
An indexed array is a type of array where each element is assigned a numeric index automatically, starting
from 0.
Each value is accessed using its index number.
Syntax of Indexed Array
Using array():
Syntax: array (value1, value2, value3, ...);
Example
<?php
$colors = array("Red", "Green", "Blue");
Echo “colors[0]”;
?>
Using short
Syntax: Syntax: $arrayName = [value1, value2, value3, ...];
Example
|Dept of Computer Science JSS College for Women Chamarajanagar|
11
III BCA PHP & MySQL UNIT 2
<?php
$fruits = ["Apple", "Banana", "Mango"];
echo $fruits[0]; // Output: Apple
?>
Manually Indexing
You can also manually specify the index for each element in an indexed array
Example
<?php
$a = [0=>"a",1=>"b"];
echo $a[0];
?>
Associative arrays
Associative arrays are arrays that use named keys that you assign to them.
An associative array in PHP is an array where each key is a string (instead of a numeric index) and
is associated with a specific value
Keys typically a string and value can be any data type
Example Associative Arrays
Using array():
<?php
$person = array(
"name" => "Ali",
"age" => 25,
"city" => "Lahore"
);
?>
Using short []
<?php
$person = [
"name" => "Ali",
"age" => 25,
"city" => "Lahore"
];
?>
Multidimensional Array
A multidimensional array is an array containing one or more arrays as its elements.
It is used to store complex data structure such as tables matrices
Syntax
1. Multidimensional Indexed Array
Using [] short
$array = [
[value1, value2],
|Dept of Computer Science JSS College for Women Chamarajanagar|
12
III BCA PHP & MySQL UNIT 2
[value3, value4],
];
Example
<?php
$students = [
[1,2,3],
[1,2,3]
];
?>
Using array ()
$multiArray = array(
array(value1, value2),
array(value3, value4)
);
Example
<?php
$marks = array(
array(85, 90, 88),
array(78, 82, 80),
array(92, 95, 94)
);
echo $marks[0][1]; // Output: 90
?>
2. Multidimensional associative Array
Using [] short
$array = [
[
"key1" => "value1",
"key2" => "value2"
],
[
"key1" => "value3",
"key2" => "value4"
]
];
Example
<?php
$students = [
[
"name" => "Ali",
"age" => 21,
"grade" => "A"
],
[
"name" => "Sara",
"age" => 22,
"grade" => "A+"
|Dept of Computer Science JSS College for Women Chamarajanagar|
13
III BCA PHP & MySQL UNIT 2
]
];
?>
Using array()
Syntax
$array = array(
array(
"key1" => "value1",
"key2" => "value2"
),
array(
"key1" => "value3",
"key2" => "value4"
)
);
Example
<?php
$students = array(
array(
"name" => "Ali",
"age" => 21,
"grade" => "A"
),
array(
"name" => "Sara",
"age" => 22,
"grade" => "A+"
),
array(
"name" => "Omar",
"age" => 20,
"grade" => "B+"
)
);
?>
Accessing Array
Accessing elements in an array in PHP is straightforward! Whether you're using indexed arrays or
associative arrays, PHP provides several ways to access the array elements.
1. Accessing Elements using index
using index we can access elements.
Example indexed arrays
<?php
$fruits = ["Apple", "Banana", "Orange"];
echo $fruits[0];
?>
|Dept of Computer Science JSS College for Women Chamarajanagar|
14
III BCA PHP & MySQL UNIT 2
Accessing Elements in an Associative Array using Index
In associative arrays, each element is associated with a key (a string) instead of a numeric index. Using
key we can access elements in associative array
Example
<?php
$person = [
"name" => "abc",
"age" => 25,
"city" => "Blore"
];
echo $person["name"];
?>
Accessing Multidimensional Arrays using index
In multidimensional arrays, you need to use multiple indices or keys to access nested elements.
Example
<?php
$students = [
["name" => "Ali", "age" => 21],
["name" => "Sara", "age" => 22]
];
echo $students[0]["name"];
echo $students[1]["age"];
?>
Using foreach Loop
If you want to access all elements in an array, you can use a foreach loop:
Example Indexed array using foreach loop
<?php
$fruits = ["Apple", "Banana", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit;
}
?>
Associative array using foreach loop
<?php
$person = [
"name" => "abc",
"age" => 25,
"city" => "Blore"
];
foreach ($person as $key => $value) {
|Dept of Computer Science JSS College for Women Chamarajanagar|
15
III BCA PHP & MySQL UNIT 2
echo "$key: $value";
}
?>
Multidimensional Array foreach loop
Example
<?php
$a=[[1,2,3],[4,5,6]];
foreach($a as $ia)
{
foreach($ia as $i)
{
echo "$i";
}
}
?>
Using for Loop (Indexed Array)
If you want to access elements by index in an indexed array, you can use a for loop:
<?php
$a = [1,2,3];
$length = count($a);
for ($i = 0; $i < $length; $i++) {
echo $a[$i];
}
?>
using print_r() function
this function is used to access all elements of array
Example for indexed array
<?php
$colors = ["red", "green", "blue"];
print_r($colors);
?>
Example for associative array
<?php
$person = [
"name" => "John",
"age" => 30,
"email" => "john@[Link]"
];
print_r($person);
?>
Example
<?php
$users = [
["name" => "Alice", "age" => 25],
|Dept of Computer Science JSS College for Women Chamarajanagar|
16
III BCA PHP & MySQL UNIT 2
["name" => "Bob", "age" => 28]
];
print_r($users);
?>
Using var_dump()
this function is used to access all elements of array
Example
<?php
$colors = ["red", "green", "blue"];
Var_dump($colors);
?>
Example for Associative array
<?php
$person = [
"name" => "John",
"age" => 30,
"email" => "john@[Link]"
];
var_dump($person);
?>
Example for multidimensional array
<?php
$users = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 28]
];
var_dump($users);
?>
Manipulating Arrays
Add Array Item
To add items to an existing indexed array, you can use the bracket []
<?php
$a = [1,2,3];
$a[] =4;
var_dump($a);
?>
Associative Arrays
To add items to an associative array, or key/value array, use brackets [] for the key, and assign value with
the = operator.
<?php
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars["color"] = "Red";
|Dept of Computer Science JSS College for Women Chamarajanagar|
17
III BCA PHP & MySQL UNIT 2
var_dump($cars);
?>
Update Array Item
To update an existing array item, you can refer to the index number for indexed arrays, and the key name for
associative arrays.
<?php
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
?>
To update items from an associative array, use the key name:
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$cars["year"] = 2024;
var_dump($cars);
?>
Remove Array Item
To remove an existing item from an array, you can use the array_splice() function.
With the array_splice() function you specify the index (where to start) and how many items you want
to delete.
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
var_dump($cars);
?>
Using the unset Function
You can also use the unset() function to delete existing array items.
<?php
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
var_dump($cars);
?>
Remove Multiple Array Items
To remove multiple items, the array_splice() function takes a length parameter that allows you to
specify the number of items to delete.
<?php
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 2);
var_dump($cars);
?>
Remove Item from an Associative Array
To remove items from an associative array, you can use the unset() function.
|Dept of Computer Science JSS College for Women Chamarajanagar|
18
III BCA PHP & MySQL UNIT 2
Specify the key of the item you want to delete.
<?php
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
var_dump($cars);
?>
DISPLAYING ARRAY
Displaying an array in PHP" means showing the contents of an array
Display indexed array
Using print_r()
Example
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
print_r($fruits);
?>
Using foreach Loop
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit;
}
?>
Using for Loop
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
$length = count($fruits);
for ($i = 0; $i < $length; $i++) {
echo "Index $i: " . $fruits[$i] . "<br>";
}
?>
Using var_dump()
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
Var_dump($fruits);
?>
Display an Associative Array
Using print_r()
<?php
$person = [
"name" => "Ali",
"age" => 25,
"city" => "Blore"
];
print_r($person);
|Dept of Computer Science JSS College for Women Chamarajanagar|
19
III BCA PHP & MySQL UNIT 2
?>
Using var_dump()
<?php
$person = [
"name" => "Ali",
"age" => 25,
"city" => "Lahore"
];
Var_dump($person);
?>
Using foreach Loop
<?php
foreach ($person as $key => $value) {
echo "$key: $value";
}
?>
Display a Multidimensional Array
Using print_r()
<?php
$students = [
["name" => "Ali", "age" => 21, "grade" => "A"],
["name" => "Sara", "age" => 22, "grade" => "A+"],
["name" => "Omar", "age" => 20, "grade" => "B"]
];
print_r($students);
?>
Using var_dump()
<?php
$students = [
["name" => "Ali", "age" => 21, "grade" => "A"],
["name" => "Sara", "age" => 22, "grade" => "A+"],
["name" => "Omar", "age" => 20, "grade" => "B"]
];
Var_dump($students);
?>
Using Nested foreach Loop
<?php
$students = [
["name" => "Ali", "age" => 21, "grade" => "A"],
["name" => "Sara", "age" => 22, "grade" => "A+"],
["name" => "Omar", "age" => 20, "grade" => "B"]
];
foreach ($students as $student) {
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
echo "<hr>"; // separates each student
|Dept of Computer Science JSS College for Women Chamarajanagar|
20
III BCA PHP & MySQL UNIT 2
}
?>
ARRAY FUNCTIONS
array()
The array () function is used to create an array.
Syntax for indexed arrays:
o array(value1, value2, value3, etc.)
Example :$nums = range(1, 5);
Syntax for associative arrays:
o array(key=>value,key=>value,key=>value);
Example array(“name”=>”abc”);
array_push()
The array_push() function inserts one or more elements to the end of an array.
Syntax : array_push(array, value1, value2, ...);
<?php
$a=array("a"=>"red","b"=>"green");
array_push($a,"blue","yellow");
print_r($a);
?>
array_unshift()
The array_unshift() function inserts new elements to an array. The new array values will be inserted in
the beginning of the array.
Syntax: array_unshift(array, value1, value2, value3, ...);
<?php
$colors = ["green", "blue"];
array_unshift($colors, "red");
print_r($colors);
?>
count()
The count() function returns the number of elements in an array.
Syntanx : count(array, mode);
a. array → The array you want to count elements in.
b. mode (optional):0 (default) – counts only the top-level elements.
1 – counts all elements recursively (for multidimensional arrays).
<?php
$fruits = ["Apple", "Banana", "Mango"];
echo count($fruits);
?>
range ()
|Dept of Computer Science JSS College for Women Chamarajanagar|
21
III BCA PHP & MySQL UNIT 2
The range() function is used to create an array containing a range of elements
Syntax :range(start, end, step);
start – Starting number or character
end – Ending number or character
step (optional) – The step between elements (default is 1)
Example
<?php
$numbers = range(1, 10);
print_r($numbers);
?>
in_array()
The in_array() function checks whether a specific value exists in an array and returns:
true if found
false if not found
syntax: in_array(value, array, strict);
value – The value to search for.
array – The array to search in.
strict (optional) – If set to true, it also checks data types.
Example
<?php
$fruits = ["Apple", "Banana", "Mango"];
if (in_array("Banana", $fruits)) {
echo "Banana is in the list!";
}
?>
Array_reverse()
The array_reverse() function takes an array and reverses its order
Syntax: array_reverse(array, preserve_keys);
array – The array you want to reverse.
preserve_keys (optional) – If set to true, it preserves the keys of the original array. By default, it's set
to false, meaning the keys are re-indexed.
Example
<?php
$fruits = ["Apple", "Banana", "Mango"];
$reversed_fruits = array_reverse($fruits);
print_r($reversed_fruits);
?>
array_pop()
The array_pop() function deletes the last element of an array.
|Dept of Computer Science JSS College for Women Chamarajanagar|
22
III BCA PHP & MySQL UNIT 2
Syntax array_pop(array);
Example
<?php
$fruits = ["Apple", "Banana", "Mango"];
$last_fruit = array_pop($fruits);
echo $last_fruit; // Output: Mango
print_r($fruits); // Output: Array ( [0] => Apple [1] => Banana )
?>
array_search()
The array_search() function searches for a given value in an array and returns the first key where the value
is found. If the value is not found, it returns false.
Syntax: array_search(value, array, strict);
value – The value you are searching for.
array – The array in which to search.
strict (optional) – If set to true, it will also check the data types (i.e., strict comparison). Default is
false, which uses loose comparison.
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange"];
$key = array_search("Banana", $fruits);
echo $key;
?>
Sort()
The sort() function sorts an indexed array in ascending order. The array is sorted by value,
Syntax sort(array, sort_flags);
array – The array you want to sort.
sort_flags (optional) – You can specify a sorting behavior
Example
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
sort($numbers);
print_r($numbers);
?>
rsort()
The rsort() function sorts an indexed array in descending order.
Syntax :rsort(array, sorttype)
|Dept of Computer Science JSS College for Women Chamarajanagar|
23
III BCA PHP & MySQL UNIT 2
Example
<?php
$numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
rsort($numbers);
print_r($numbers);
?>
Kosrt()
The ksort() function sorts an associative array in ascending order, according to the key.
Syntax :ksort(array, sorttype)
<?php
$person = [
"name" => "Ali",
"age" => 25,
"city" => "Lahore"
];
ksort($person);
print_r($person);
?>
krsort()
The krsort() function sorts an associative array in descending order, according to the key.
Syntax: krsort(array, sorttype)
Example
<?php
$person = [
"name" => "Ali",
"age" => 25,
"city" => "Blore"
];
krsort($person);
print_r($person);
?>
array_unique()
array_unique() removes duplicate values from an array and returns a new array with only the first
occurrence of each value.
Syntax: array_unique(array $array, int $flags = SORT_STRING);
$array: The input array.
$flags (optional): Sorting behavior (SORT_STRING, SORT_NUMERIC, etc.).
Example
<?php
$fruits = ["apple", "banana", "apple", "orange", "banana"];
$uniqueFruits = array_unique($fruits);
print_r($uniqueFruits);
|Dept of Computer Science JSS College for Women Chamarajanagar|
24
III BCA PHP & MySQL UNIT 2
?>
unset()
The unset() function destroys a specified variable or element
Syntax: unset($variable);
Example
<?php
$fruits = ["apple", "banana", "cherry"];
unset($fruits[1]);
print_r($fruits);
?>
array_flip()
array_flip() exchanges the keys with their corresponding values in an array.
Syntax: array_flip(array $array);
a. Takes one array as input.
b. Returns a new array where the keys become values and values become keys.
Example
<?php
$nums = [10 => "one", 20 => "two", 30 => "three"];
$flipped = array_flip($nums);
print_r($flipped);
?>
Difference between Indexed and Associative array or Indexed v/s Associative arrays
Including and Requiring Files- use of Include () and Require
The include or require statement takes all the text/code/markup that exists in the specified file and
copies it into the file that uses the include statement.
OR
The include or require statement can be used to insert the content of one PHP file into another PHP file
|Dept of Computer Science JSS College for Women Chamarajanagar|
25
III BCA PHP & MySQL UNIT 2
Include in php will only generate an alert (E_WARNING) and the script will proceed
Require will produce a fatal error (E_COMPILE_ERROR) and interrupt the script
Include
Include is a keyword to include one php file into another PHP file
If the file not be found warning is generated but the script will continue execution
Syntax: include('filename');
filename – The path to the file you want to include. This can be a relative or absolute file path.
Example
[Link]
<?php
echo “hello”;
?>
[Link]
<?php
Include‘[Link]’;
Echo “bye”;
?>
Include_once
the include_once keyword is used to embed PHP code from another file. The file is included only once
during script execution
If the file was already included previously, this statement will not include it again.
Example [Link]
<?php
echo “hello”;
?>
[Link]
<?php
include_once '[Link]';
include_once '[Link]';
Echo “bye”;
?>
Require
|Dept of Computer Science JSS College for Women Chamarajanagar|
26
III BCA PHP & MySQL UNIT 2
Require statement is similar to include means is used to include one file into another file but with a
crucial difference
If the file can not be found it will generate fatal error and stop the script execution
Syntax” require ‘file_name”;
Example [Link]
<?php
echo “hello”;
?>
[Link]
<?php
require '[Link]';
Echo “bye”;
?>
require_once
If the file was already included previously, this statement will not include it again.
Example [Link]
<?php
echo “hello”;
?>
[Link]
<?php
require_once '[Link]';
require_once '[Link]';
Echo “bye”;
?>
Implicit and Explicit Casting in PHP or Type casting (Type Conversion)
Type casting means converting one data type into another (like turning a string into an integer, or a
float into a string).
PHP is a loosely typed language, so it often does this automatically (implicit), but you can also force
it to do so (explicit).
Implicit casting:
PHP automatically converts data types when needed — this is also called type juggling.
Example
<?php
$x = "5" + 2; // "5" is a string, 2 is an integer
echo $x;
?>
|Dept of Computer Science JSS College for Women Chamarajanagar|
27
III BCA PHP & MySQL UNIT 2
Explicit Type Casting (Manual Casting)
When you explicitly convert a variable to another type using type casting syntax. Is called Explicit Type
Casting
There are several ways we can convert
Casting with type:
Syntax: $newValue = (type) $originalValue;
Example
<?php
$val = "42";
$intVal = (int)$val;
echo $intVal + 8; // Output: 50
?>
Using functions in PHP
We have built-in functions in PHP we can do Explicit type casting using those functions
Function Purpose
intval() Convert to integer
floatval() Convert to float
strval() Convert to string
boolval() Convert to boolean
settype() Force a variable to a type
Example
<?php
$val = "123.45";
$intVal = intval($val); // 123
$floatVal = floatval($val); // 123.45
?>
Using array () function
Array can be used to convert value into array
Ex:
<?php
$a=”hello”;
$b=array($a);
Print_r($b);
?>
|Dept of Computer Science JSS College for Women Chamarajanagar|