Unit - II
2. Programming with PHP 15
2.1 Conditional statements: if, if-else, switch, The ? Operator
2.2 Looping statements: while Loop, do...while Loop, for Loop
2.3 Arrays in PHP: Introduction- What is Array?
2.4 Types of Arrays: Indexed Vs. Associative arrays, Multidimensional arrays
2.5 Creating Array, Accessing Array, Manipulating Arrays, Displaying arrays,
use of for.. each as loop
2.6 Using Array Functions
2.7 Including and Requiring Files- use of Include() and Require()
2.8 Implicit and Explicit Casting in PHP
2.1 Conditional statements: if, if-else, switch, The ? : Operator
Conditional statements:
Conditional statements are used to take decision based on the different condition. You can use
conditional statements in your code to make your decisions.
PHP supports following decision making statements −
1. if statement - executes some code if one condition is true
2. if...else statement − use this statement if you want to execute a set of code when a
condition is true and another if the condition is not true
3. switch statement − is used if you want to select one of many blocks of code to be
executed, use the Switch statement. The switch statement is used to avoid long blocks
of if..elseif..else code.
1) if statement:
The if statement executes some code if one condition is true.
1
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Syntax
if (condition) {
// code to be executed if condition is true;
}
Example
if (5 > 3) {
echo "5 is larger than 3!";
}
Output: 5 is larger than 3!
Note: program executes if condition is true, on false no if block executed.
2) if...else Statement
If you want to execute some code if a condition is true and another code if a condition is false,
use the if else statement.
Syntax
if (condition)
code to be executed if condition is true;
else
code to be executed if condition is false;
Example:
The following example will output "Have a nice weekend!" if the current day is Friday,
Otherwise, it will output "Have a nice day!":
<html>
<head><title>Demo</title></head>
<body>
<?php
$marks = 55;
if ($marks >=30)
{ echo "You are PASS!"; }
else
{ echo "You are FAIL!"; }
?>
</body>
</html>
Output − You are PASS!
2
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
3) Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax
switch (expression)
{
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and label2;
}
Example
The switch statement works in an unusual way. First it evaluates given expression then seeks a
label to match the resulting value. If a matching value is found then the code associated with
the matching label will be executed or if none of the label matches then statement will execute
any specified default code.
<html>
<head><title>Demo</title></head>
<body>
<?php
$day = date("D");
switch ($day)
{
case "Mon":
echo "Today is Monday"; break;
case "Tue":
echo "Today is Tuesday"; break;
case "Wed":
echo "Today is Wednesday"; break;
case "Thu":
echo "Today is Thursday"; break;
case "Fri":
echo "Today is Friday"; break;
case "Sat":
3
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
echo "Today is Saturday"; break;
case "Sun":
echo "Today is Sunday"; break;
default:
echo "Input is not in proper format ?";
}
?>
</body>
</html>
It will produce the following result if today is Monday: “Today is Monday”
The ? : Operator
This is the conditional operator. It is used as ternary operator that means it has three operands. It
is short form for simple if-else statements.
The conditional ternary operator is a concise way to express an if-else statement in a single line,
often used for simple conditional assignments.
It takes three operands: a condition, a consequent expression (executed if the condition is true),
and an alternative expression (executed if the condition is false).
The syntax
condition ? consequent : alternative.
condition ? True : False.
Condition: A Boolean expression that is evaluated.
? Separates the condition from the expressions.
Consequent: The expression that is executed if the condition is true.
: Separates the consequent and alternative expressions.
Alternative: The expression that is executed if the condition is false.
Example: This is equivalent to:
$age = 20; $age = 20;
$status = $age >= 18 ? "Adult" : "Minor"; $status = null;
echo $status; if ($age >= 18)
{ echo $status = "Adult"; }
else
{ echo $status = "Minor"; }
Output: Adult Output: Adult
4
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
2.2 Looping statements: while Loop, do...while Loop, for Loop:
PHP supports following loop types.
1. while − loops through a block of code if and as long as a specified condition is true.
2. do...while − loops through a block of code once, and then repeats the loop as long as a special
condition is true.
3. for − loops through a block of code a specified number of times.
1) While Loop:
The condition is checked before the loop's
body is executed in each iteration.
The while loop executes a block of code as
long as the specified condition is true.
If the condition is initially false, the loop's
body will not execute even once.
Syntax Example Output
while (condition is true) <?php The number is: 1
{ $x = 1; The number is: 2
code to be executed; while($x <= 5) { The number is: 3
} echo "The number is: $x <br>"; The number is: 4
$x++; The number is: 5
}
?>
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to run as long
as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop runs ($x++):
2) Do...While Loop:
The loop's body is executed at least once
before the condition is checked for the first
time.
The condition is checked after the loop's
body is executed in each iteration.
This guarantees that the code within the do
block will run at least once, regardless of
whether the condition is initially true or false.
Syntax Example Output
do { <?php The number is: 1
code to be executed; $x = 1; The number is: 2
} do { The number is: 3
while (condition is true); echo "The number is: $x <br>"; The number is: 4
$x++; The number is: 5
} while ($x <= 5);
?>
5
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some output, and
then increment the variable $x with 1. Then the condition is checked (is $x less than, or equal to 5?), and
the loop will continue to run as long as $x is less than, or equal to 5:
3) for Loop:
For Loops generally used when you know the number of iterations in advance or when you need to iterate
over a sequence (like a list, array, or string). They clearly communicate that intent upfront by consolidating
initialization, condition, and increment/decrement within the loop header.
Parameters:
init counter: Initialize the loop counter value
condition: checks for each loop iteration. If it is TRUE, the loop continues. If it is FALSE, the loop
ends.
increment counter: Increases the loop counter value The example below displays the numbers
from 0 to 10:
Syntax Example Output
for (init counter; condition; increment) <?php The number is: 1
{ for ($x = 1; $x <= 5; $x++) The number is: 2
code to be executed; { The number is: 3
} echo "The number is: $x <br>"; The number is: 4
} The number is: 5
?>
Practice Example of Nested For Loop: Program to print multiplication table from 2 to 20
<h1>Multiplication Table from 2 to 20</h1><hr>
<table border="1">
<?php
for($i=1; $i<=10; $i++)
{
print "<tr>";
for($j=2; $j<=20; $j++)
{
print "<td>".($i*$j)."</td>";
}
print "</tr>";
}
?>
</table>
6
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
2.3 Arrays in PHP: Introduction- What is Array?
An array is a fundamental data structure in computer science that stores a collection of elements,
typically of the same data type, in contiguous memory locations. It allows for efficient access to
individual elements using their index, which is a numerical representation of their position within
the array.
Linear Structure & Contiguous Memory:
Elements are arranged sequentially, one after another, in memory.
Same Data Type:
All elements in the array must be of the same data type (e.g., all integers, all floating -point
numbers, or all characters).
Index-based access:
Each element in an array has a numerical index, starting from 0 for the first element. This index is
used to retrieve or modify a specific element.
Fixed size:
Arrays usually have a fixed size, meaning the number of elements they can hold is determined
when the array is created and cannot be changed later.
One-dimensional Array :
Arrays can be one-dimensional (like a list)
Example:
Consider an array named myarray that stores the integers 2,4,8,12,16, and 18.
In memory, these values would be stored contiguously, and you could access those using
index numbers, which would be like index0, index1, index2 and so on.
We can access array element using their appropriate index number suppose we write as
myarray[2] it means that we want to access value from myarray which is stored in memory
with label as index number 2.
7
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Multidimensional Array :
Multidimensional (like a table or matrix).
A two-dimensional array or 2D array is the simplest form
of the multidimensional array. We can visualize a two-
dimensional array as one-dimensional arrays stacked
vertically forming a table with rows and columns.
In PHP, arrays are 0-indexed, so the row number ranges
from 0 to (rows-1) and the column number ranges from
0 to (columns-1).
2.4 Types of Arrays: Indexed Vs. Associative arrays, Multidimensional arrays
PHP supports three main types of arrays:
1) Indexed arrays
2) Associative arrays
3) Multidimensional arrays.
1. Indexed arrays (or numeric arrays):
Definition: These arrays use numeric indexes (keys) to store and access values.
Indexed array is an array in which each value in the array has integer index or integer keys.
The keys of an indexed array are integers, beginning at 0.
Indexed arrays are used when you identify things by their position.
Creation:
Using short array syntax: $colors = ["Red", "Green", "Blue"];
Manually assigning values with indexes: $fruits[0] = "Apple";
Example:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Outputs: Apple
?>
Create the array of strings Create the array of five numbers
<?php <?php
$season[0]="summer"; $a[0] = 10;
$season[1]="winter"; $a[1] = 20;
$a[2] = 30;
$season[2]="spring";
$a[3] = 40;
$season[3]="autumn";
$a[4] = 50;
8
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
echo "Season are: $season[0], $season[1], echo $a[3]; //Output: 40
$season[2] and $season[3]"; ?>
?>
2. Associative arrays:
Definition: These arrays use named keys (strings or integers) to store and access values, providing
a more descriptive way to access data.
Keys: Keys can be any data type, including strings, integers, and floats, though string keys are
more commonly used for better readability.
Example: String Key
<?php
$person = ["name" => "John", "age" => 30, "city" => "New York"];
echo $person["name"]; // Outputs: John
?>
Example: Integer Key
<?php
$data_array_1 = [1 => "Value for key 1", 5 => "Value for key 5", 10 => "Value for key 10"];
?>
3. Multidimensional arrays:
Definition: These arrays contain one or more arrays as elements, allowing you to store complex
data structures, similar to tables or grids.
Nesting: Multidimensional arrays are created by nesting arrays within arrays.
Accessing elements: You need multiple indices to access elements in a multidimensional array
(e.g., two for a two-dimensional array).
Example (Two-dimensional array):
<?php
$students = array(
"Anjali" => array("age" => 25, "grade" => "A"),
"Kumar" => array("age" => 22, "grade" => "B")
);
echo $students["Kumar"]["age"]; // Outputs: 22
?>
Highlights:
9
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Arrays in PHP are versatile and can hold values of different data types.
PHP automatically assigns numeric indexes to indexed arrays, starting from 0.
Associative arrays allow you to use descriptive string keys, making code more readable and
intuitive.
Multidimensional arrays allow you to create nested data structures for representing tabular
or hierarchical information.
PHP offers numerous built-in functions to manipulate and iterate over arrays effectively.
2.5 Creating Array, Accessing Array, Manipulating Arrays, Displaying arrays, use of for.. each
as loop
Creating Arrays
PHP arrays can be created using the array() construct or by using square brackets [] (short array
syntax). Arrays can be indexed (numeric keys), associative (string keys), or multidimensional.
Code
<?php
// Indexed array
$indexedArray = array("Apple", "Banana", "Cherry");
$indexedArrayShort = ["Apple", "Banana", "Cherry"];
// Associative array
$associativeArray = array("fruit1" => "Apple", "fruit2" => "Banana");
$associativeArrayShort = ["fruit1" => "Apple", "fruit2" => "Banana"];
?>
Accessing Arrays
Elements in an array are accessed using their respective keys (index for indexed arrays, key name
for associative arrays) within square brackets.
Code
<?php
echo $indexedArray[0]; // Output: Apple
echo $associativeArray["fruit1"]; // Output: Apple
?>
Manipulating Arrays
PHP provides numerous functions for manipulating arrays.
Code
<?php
// Adding elements
array_push($indexedArray, "Mango"); // Adds to the end
$indexedArray[] = "Elderberry"; // Adds to the end
10
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
array_unshift($indexedArray, "Apricot"); // Adds to the beginning
// Removing elements
array_pop($indexedArray); // Removes from the end
array_shift($indexedArray); // Removes from the beginning
// Modifying elements
$indexedArray[1] = "Blueberry";
// Sorting
sort($indexedArray); // Sorts by value (indexed)
asort($associativeArray); // Sorts by value (associative)
ksort($associativeArray); // Sorts by key (associative)
?>
Displaying Arrays
Arrays can be displayed using print_r() or var_dump() for structured output, or by looping through
them.
Code
<?php
print_r($indexedArray);
var_dump($associativeArray);
?>
Using foreach Loop
The foreach loop is ideal for iterating over array elements, especially when you need to access
both keys and values in associative arrays.
Code
<?php
foreach ($indexedArray as $value) {
echo $value . "<br>";
}
foreach ($associativeArray as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
11
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
2.6 Using Array Function
Indexed Array Using array() function:
Create the array of strings Create the integer array of five
elements using for and for each loop
<?php <?php
$season=array("summer","winter","spring","autumn"); $num=array(10,20,30,40,50);
echo "Season are: $season[0], $season[1], $season[2] $size=count($num);
$range = $size-1;
and $season[3]";
for($i=0; $i<=$range; $i++)
?>
{
print $num[$i]."<br>";
}
// OR
foreach($num as $val)
{
echo $val. "\n";
} ?>
Associative Array using array() function ( => arrow operator):
$salary=array("Sanjay"=>35000, "John"=>45000, "Kartik"=>20000);
You can specify an initial key with => and then a list of values. The values are inserted into the array
starting with that key.
Example: (Mix value)
<?php Output:
$car = array("brand"=>"Jaguar", "model"=>"Land Rover", "year"=>1948); Brand: Jaguar
foreach ($car as $value) {
Model: Land Rover
echo "$value <br>";
Year: 1948
}
?>
12
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
2.7 Including and Requiring Files- use of Include() and Require():
PHP provides the facility to combine one or more files together to create a single page. It
allows dividing the scripts and web page into two or more parts. So the commonly used
processes or files can be designed separately & can be combined with any webpage.
Generally titles of the website, menus & some photos or some common
information/contents are displayed on every page of website.
So this can be separately designed & included into every page instead of designing it on
every page of website.
PHP Provides Two functions for this:
1. include()
2. require()
To use them, your PHP script would have a line like
include (‘[Link]’); or require (‘/path/to/[Link]’);
An important consideration with included files is that PHP treats the included code as HTML.
The included file may be .php, .html, or .txt. Also note that you can use either absolute or
relative paths to the included file.
An absolute path is a path where a file is starting from the root directory of the computer.
Such paths are always correct, For example, a PHP script can include a file using
include (‘C:/php/includes/[Link]’);
A relative path uses the referencing (parent) file as the starting point. To move up one folder,
use two periods together. To move into a folder, use its name followed by a slash. So assuming
the current script is in the www/ex1 folder and you want to include something in www/ex2,
the code would be:
include(‘../ex2/[Link]’);
A relative path will remain accurate, even if moved to another server, as long as the files keep
their current relationship.
include() and require() functions are exactly the same when working properly but behave
differently when they fail.
13
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Differences:
include() require()
If include() function doesn’t work (means If require() fails, an error is printed and the
it cannot include the file for some reason), script execution is stopped.
a warning will be printed to the Web
browser, but the script will continue to run.
Example:
Assume that you have a web page [Link] and you want to place some repleated code inside
an isolated standard file, for header content to carry logo image and company name it is
"[Link]". In the same way for copyright footer content “[Link]” and all navigation
content it’s also called menu put in “[Link]” file. If we look out this we found that all code
present in three different php files and we need to bind it together so we have to use include()
or require(). To include the header file, footer file and menu file together in a webpage, use the
include() function, we include header, footer and menu inside [Link] file like this:
File Part 1: [Link] File Part 2: [Link] File Part 3: [Link]
<img src=”[Link]” <center> <hr>
align=”left”/> Copyright © <a href="[Link]">Home</a>|
<h1 align=”center”> <?php echo date('Y'); ?> <a href="[Link]">About
Company Name</h1> Company Name Us</a> |
</center> <a href="[Link]">Contact
Us</a> <hr>
Main File 1: [Link]
<html>
<body>
<?php include("[Link]"); ?>
<?php include("[Link]"); ?>
<h1>Welcome to my home page</h1>
<p>Some text</p>
All content …
<?php include("[Link]"); ?>
</body>
</html>
14
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Output:
When they all combine and get together with main code those three files and main file will
produce following output.
2.8 Implicit and Explicit Casting in PHP:
In PHP, type casting refers to the conversion of a value from one data type to another. This can
occur either implicitly (automatically by PHP) or explicitly (by the programmer's instruction).
What is Type Casting?
Type casting is a concept in programming where you change the data type of a variable from
one type to another. It's like changing a piece of clay from one shape to another.
There are two types of type casting: implicit and explicit.
1. Implicit Type Casting (Automatic):
2. Explicit Type Casting (Manual):
1. Implicit Casting (Automatic):
Implicit type casting, the programming language automatically converts data from one type to
another if needed. For example, if you have an integer variable and you try to assign it to a float
variable, the programming language will automatically convert the integer to a float without
you having to do anything.
15
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
Example: When performing arithmetic operations involving different data types (e.g., adding
an integer to a float), PHP will automatically convert one of the values to a compatible type to
perform the calculation. If you add a string containing a numeric value to a number, PHP will
attempt to convert the string to a number.
Code:
<?php
$integer = 5;
$float = 2.5;
$result = $integer + $float; // $integer is implicitly converted to a float
echo $result; // Output: 7.5
$string_number = "10";
$number = 5;
$sum = $string_number + $number; // $string_number is implicitly converted to
an integer
echo $sum; // Output: 15
?>
Advantages:
Convenience: Implicit casting saves time and effort because you don't have to manually
convert data types.
Automatic: It happens automatically, reducing the chance of errors due to forgetting to
convert types.
Disadvantages:
1. Loss of Precision: Sometimes, when converting between data types, there can be a loss of
precision. For example, converting from a float to an integer may result in losing the decimal
part of the number.
2. Unexpected Results: Implicit casting can sometimes lead to unexpected results if the
programmer is not aware of how the conversion rules work.
2. Explicit Type Casting (Manual):
Explicit type casting, also known as type conversion or type coercion, Explicit casting
involves the programmer directly instructing PHP to convert a value to a specific data type
using casting operators. This provides more control over the conversion process.
Syntax: (target_type) $variable_name
Common Casting Operators:
(int) or (integer): Converts to an integer.
(float) or (double) or (real): Converts to a float.
16
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)
(string): Converts to a string.
(bool) or (boolean): Converts to a boolean.
(array): Converts to an array.
(object): Converts to an object.
(unset): Converts to NULL (effectively unsetting the variable).
Code
<?php
$float_value = 7.89;
$integer_value = (int) $float_value; // Explicitly cast to integer
echo $integer_value; // Output: 7 (fractional part is truncated)
$number_as_string = 123;
$string_converted = (string) $number_as_string; // Explicitly cast to string
var_dump($string_converted); // Output: string
?>
Advantages:
Control: Explicit type casting gives the programmer more control over the conversion
process, allowing for precise manipulation of data types.
Clarity: By explicitly indicating the type conversion, the code becomes more readable and
understandable to other developers.
Avoidance of Loss of Precision: In cases where precision is crucial, explicit type casting
allows the programmer to handle the conversion carefully to avoid loss of precision.
Disadvantages:
Complexity: Explicit type casting can introduce complexity to the code, especially when
dealing with multiple data type conversions.
Potential Errors: If the programmer incorrectly performs explicit type casting, it may result
in runtime errors or unexpected behaviour.
Additional Syntax: Explicit type casting requires additional syntax or function calls, which
may increase code verbosity.
THE END
17
B.C.A. Third Year Semester V Subject: Web Development and PHP Programming (Code: BCA-502)