UNIT – 3
WEB PROGRAMMING
Introduction to PHP
Introduction
PHP (Hypertext Preprocessor) is an open-source, server-side scripting
language primarily used for web development. It can be embedded into
HTML to create dynamic and interactive web pages.
Structure of PHP
A PHP script starts with the <?php tag and ends with the ?> tag.
<?php
echo "Hello, World!";
?>
All PHP code must be written inside these tags for the server to recognize
and process it.
Using Comments
Comments are used to document code and improve readability. PHP
supports three types of comments:
// Single-line comment
# Single-line comment (alternative style)
/* Multi-line
comment */
Comments are ignored by the PHP interpreter.
Comments are ignored by the PHP interpreter; they are for human
readability and maintainability.
They help document what a piece of code is meant to do, especially in
teaching, debugging, or when revisiting code later.
Good practice: add comments for non-obvious logic, functions, variable
roles, etc.
Program:
<?php
// This is a single-line comment
# This is also a single-line comment
/*
This is a multi-line comment.
You can write multiple lines of notes here.
Comments are ignored by the PHP interpreter.
*/
// Declare a variable
$name = "Harshitha";
// Display the message
echo "Welcome, $name!";
?>
Basic Syntax
PHP statements end with a semicolon (;). PHP code is case-sensitive for
variables but not for keywords.
<?php
$name = "Harsha";
echo $name;
?>
Case sensitivity: variable names are case-sensitive ($Var ≠ $var),
function names are not strictly case-sensitive but best practice is
consistent use.
PHP keywords (if, else, echo, etc.) are not valid as variable names.
Wikipedia+1
PHP variables must start with a dollar sign ($) followed by a letter or
underscore, then any number of letters, numbers or underscores. Self-
Taught Coders
Strings can be enclosed in single quotes or double quotes; double
quotes allow variable interpolation, single quotes do not.
Variables
Variables in PHP are declared with the $ symbol and can store different
types of data (strings, integers, arrays, etc.).
• Must start with a letter or underscore _.
• Cannot start with a number.
• Are case-sensitive.
$name = "John";
$age = 25;
Program:
<?php
// This program demonstrates variable declaration and usage in PHP
// Declaring variables
$name = "Harisha"; // String variable
$age = 21; // Integer variable
$height = 5.8; // Float variable
$isStudent = true; // Boolean variable
// Displaying variables
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Height: " . $height . " feet<br>";
echo "Student Status: " . ($isStudent ? "Yes" : "No") . "<br>";
// Changing variable value
$age = $age + 1; // Increment age
echo "Next Year Age: " . $age;
?>
Output:
Name: Harisha
Age: 21
Height: 5.8 feet
Student Status: Yes
Next Year Age: 22
Operators
Operators perform operations on variables and values.
• Arithmetic Operators: +, -, *, /, %
• Assignment Operators: =, +=, -=, *=, /=, %=
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
$a = 10;
$b = 20;
echo $a + $b; // Output: 30
Program:
<?php
// Program: Demonstrating different types of Operators in PHP
Arithmetic Operators
$a = 10;
$b = 3;
echo "<h3>1. Arithmetic Operators</h3>";
echo "a + b = " . ($a + $b) . "<br>";
echo "a - b = " . ($a - $b) . "<br>";
echo "a * b = " . ($a * $b) . "<br>";
echo "a / b = " . ($a / $b) . "<br>";
echo "a % b = " . ($a % $b) . "<br><br>";
Assignment Operators
echo "<h3>2. Assignment Operators</h3>";
$c = $a; // simple assignment
echo "c = " . $c . "<br>";
$c += 5; // equivalent to c = c + 5
echo "c += 5 → " . $c . "<br>";
$c -= 3; // equivalent to c = c - 3
echo "c -= 3 → " . $c . "<br><br>";
Comparison Operators
echo "<h3>3. Comparison Operators</h3>";
$x = 10;
$y = "10";
echo "x == y : "; var_dump($x == $y); echo "<br>"; // true (same value)
echo "x === y : "; var_dump($x === $y); echo "<br>"; // false (different
type)
echo "x != y : "; var_dump($x != $y); echo "<br>"; // false
echo "x !== y : "; var_dump($x !== $y); echo "<br><br>"; // true
Logical Operators
echo "<h3>4. Logical Operators</h3>";
$age = 20;
$citizen = true;
if ($age >= 18 && $citizen) {
echo "Eligible to vote<br>";
}
if ($age < 18 || !$citizen) {
echo "Not eligible to vote<br>";
}
// 5️⃣ String Operators
echo "<h3>5. String Operators</h3>";
$first = "Hello";
$second = "World";
echo $first . " " . $second . "<br>"; // concatenation
$first .= " PHP"; // concatenation assignment
echo $first . "<br><br>";
// 6️⃣ Increment/Decrement Operators
echo "<h3>6. Increment/Decrement Operators</h3>";
$num = 5;
echo "Original number: " . $num . "<br>";
echo "Pre-increment: " . (++$num) . "<br>"; // increases before using
echo "Post-increment: " . ($num++) . "<br>"; // uses, then increases
echo "After post-increment: " . $num . "<br>";
echo "Pre-decrement: " . (--$num) . "<br>";
echo "Post-decrement: " . ($num--) . "<br>";
echo "After post-decrement: " . $num . "<br><br>";
// 7️⃣Conditional (Ternary) Operator
echo "<h3>7. Conditional (Ternary) Operator</h3>";
$marks = 75;
$result = ($marks >= 40) ? "Pass" : "Fail";
echo "Result: " . $result . "<br>";
?>
Output:
1. Arithmetic Operators
a + b = 13
a-b=7
a * b = 30
a / b = 3.3333333333
a%b=1
2. Assignment Operators
c = 10
c += 5 → 15
c -= 3 → 12
3. Comparison Operators
x == y : bool(true)
x === y : bool(false)
x != y : bool(false)
x !== y : bool(true)
4. Logical Operators
Eligible to vote
5. String Operators
Hello World
Hello PHP
6. Increment/Decrement Operators
Original number: 5
Pre-increment: 6
Post-increment: 6
After post-increment: 7
Pre-decrement: 6
Post-decrement: 6
After post-decrement: 5
7. Conditional (Ternary) Operator
Result: Pass
Variable Assignment
Assignment is done using the = operator. PHP allows assigning by value or
by reference.
$x = 5; // Value assignment
$y =& $x; // Reference assignment
Changing $y will also change $x in reference assignment.
Multiple-Line Commands
Multiple statements can be written across several lines. Each must end
with a semicolon.
<?php
$sum = 10 + 20;
$avg = $sum / 2;
echo $avg;
?>
Program:
<?php
// Program: Demonstrating Multiple-Line Commands in PHP
/*
In PHP, a single statement can be written
on multiple lines for better readability.
Each statement must end with a semicolon (;)
even if it spans several lines.
*/
// Example 1: Multi-line variable assignment
$message = "Welcome "
. "to "
. "PHP Programming!";
echo $message . "<br><br>";
// Example 2: Multi-line array declaration
$student = array(
"name" => "Harisha",
"course" => "BCA",
"year" => 2025,
"marks" => array(
"PHP" => 90,
"Python" => 88,
"DBMS" => 92
)
);
// Printing array values
echo "Student Name: " . $student["name"] . "<br>";
echo "Course: " . $student["course"] . "<br>";
echo "Year: " . $student["year"] . "<br>";
echo "Marks in PHP: " . $student["marks"]["PHP"] . "<br>";
?>
Output:
Welcome to PHP Programming!
Student Name: Harsha
Course: BCA
Year: 2025
Marks in PHP: 90
Variable Typing
PHP is loosely typed, meaning variable types are determined at runtime.
The same variable can store different data types.
$x = 5; // Integer
$x = "Five"; // String
Program:
<?php
// Program: Demonstrating Variable Typing in PHP
/*
PHP automatically determines the data type of a variable
based on the value assigned to it.
*/
// Assigning different data types to the same variable
$var = 10; // Integer
echo "Value: $var, Type: " . gettype($var) . "<br>";
$var = 10.75; // Float
echo "Value: $var, Type: " . gettype($var) . "<br>";
$var = "Hello PHP"; // String
echo "Value: $var, Type: " . gettype($var) . "<br>";
$var = true; // Boolean
echo "Value: $var, Type: " . gettype($var) . "<br>";
$var = array(1, 2, 3); // Array
echo "Type: " . gettype($var) . "<br>";
$var = null; // NULL
echo "Type: " . gettype($var) . "<br>";
?>
Output:
Value: 10, Type: integer
Value: 10.75, Type: double
Value: Hello PHP, Type: string
Value: 1, Type: boolean
Type: array
Type: NULL
Constants
Constants are identifiers for fixed values that cannot change during script
execution. Defined using the define() function.
define("SITE_NAME", "MyWebsite");
echo SITE_NAME;
Constants do not start with $ and are global by default.
Predefined Constants
PHP provides several predefined constants:
• __FILE__ – Full path and filename of the file.
• __LINE__ – Current line number.
• PHP_VERSION – Current PHP version.
• PHP_OS – Operating system PHP is running on.
echo PHP_VERSION;
Constants in PHP are defined via the define() function or the const
keyword (PHP 5.3+). For example:
define("PI", 3.14159);
const MAX_USERS = 1000;
Constants are global in scope and cannot be changed once set.
Predefined constants: PHP has many built-in constants (e.g.,
PHP_VERSION, PHP_OS, E_ERROR, etc.). These allow querying the
runtime environment.
For example:
echo "You are running PHP version: " . PHP_VERSION;
Using constants helps avoid "magic numbers" and improves readability
and maintainability.
Program:
<?php
// Program: Demonstrating Constants in PHP
/*
Constants are defined using the define() function.
Syntax: define(name, value, case_insensitive)
*/
// Defining constants
define("SITE_NAME", "BCA PHP Tutorial");
define("YEAR", 2025);
define("PI", 3.14159);
// Displaying constants
echo "<h3>1. User-defined Constants</h3>";
echo "Website Name: " . SITE_NAME . "<br>";
echo "Year: " . YEAR . "<br>";
echo "Value of PI: " . PI . "<br><br>";
// Trying to change constant value (This will NOT work)
echo "Attempting to change constant...<br>";
// SITE_NAME = "New Name"; // ❌ Error: constants cannot be changed
// Using constants inside a function
function showConstant() {
echo "Accessing constant inside function: " . SITE_NAME . "<br>";
}
showConstant();
// Predefined Constants
echo "<h3>2. Predefined Constants</h3>";
echo "PHP Version: " . PHP_VERSION . "<br>";
echo "Operating System: " . PHP_OS . "<br>";
echo "Current File: " . __FILE__ . "<br>";
echo "Current Line: " . __LINE__ . "<br>";
?>
Output:
1. User-defined Constants
Website Name: BCA PHP Tutorial
Year: 2025
Value of PI: 3.14159
Attempting to change constant...
Accessing constant inside function: BCA PHP Tutorial
2. Predefined Constants
PHP Version: 8.2.12
Operating System: WINNT
Current File: C:\xampp\htdocs\[Link]
Current Line: 29
Difference Between echo and print
Feature echo print
Return Value No Returns 1
Faster, outputs Slightly slower, used for
Usage
multiple strings single string
Example echo "Hello"; print "Hello";
Both are used to output data
to the browser.
Functions
Functions are reusable blocks of code. They make the program modular
and easier to maintain.
function greet($name) {
echo "Hello, $name!";
}
greet("John");
Variable Scope
PHP variables have four types of scope:
• Local – Declared inside a function.
• Global – Declared outside a function.
• Static – Retains value between function calls.
• Parameter – Passed into a function.
$globalVar = 10;
function test() {
global $globalVar;
echo $globalVar;
}
test();
Program:
<?php
// Program: Demonstrating Variable Scope in PHP
// Global variable
$globalVar = 10;
function testScope() {
// Local variable
$localVar = 5;
echo "<h4>Inside Function:</h4>";
echo "Local Variable: $localVar <br>";
// Accessing global variable using 'global' keyword
global $globalVar;
echo "Global Variable (using global keyword): $globalVar <br>";
// Static variable retains value between function calls
static $count = 0;
$count++;
echo "Static Variable (count): $count <br>";
}
testScope(); // First call
testScope(); // Second call
testScope(); // Third call
echo "<h4>Outside Function:</h4>";
// Accessing global variable directly
echo "Global Variable (outside function): $globalVar <br>";
// Trying to access local variable (will cause an error if uncommented)
// echo $localVar; // ❌ Undefined variable error
// Function parameter scope
function greet($name) {
echo "Hello, $name!<br>";
}
greet("Harisha");
?>
Output:
Inside Function:
Local Variable: 5
Global Variable (using global keyword): 10
Static Variable (count): 1
Inside Function:
Local Variable: 5
Global Variable (using global keyword): 10
Static Variable (count): 2
Inside Function:
Local Variable: 5
Global Variable (using global keyword): 10
Static Variable (count): 3
Outside Function:
Global Variable (outside function): 10
Hello, Harisha!
Expressions and Control Flow
Expressions combine variables and operators to produce a value.
Control flow structures determine the order of code execution:
• if / else / elseif
• switch
• for, while, do...while, foreach
$marks = 85;
if ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
Operators and Control Statements in PHP
Introduction
Operators and control statements are the building blocks of PHP
programming. Operators allow mathematical and logical operations, while
control statements determine the flow of program execution.
2. Operators in PHP
Operators are symbols that perform operations on variables and values.
Types of Operators:
1. Arithmetic Operators
2. Assignment Operators
3. Comparison (Relational) Operators
4. Logical Operators
5. Increment/Decrement Operators
6. String Operators
7. Array Operators
8. Conditional (Ternary) Operator
Example:
$a = 10;
$b = 5;
echo $a + $b; // Output: 15
Operator Precedence
Operator precedence determines the order in which operators are
evaluated.
Example:
echo 10 + 5 * 2; // Output: 20 (Multiplication has higher precedence)
Order of Precedence (High to Low):
1. Parentheses ()
2. Increment/Decrement ++, --
3. Multiplication, Division, Modulus *, /, %
4. Addition, Subtraction +, -
5. Comparison ==, !=, >, <, >=, <=
6. Logical &&, ||
7. Assignment =
Associativity
When two operators have the same precedence, associativity determines
the evaluation order.
• Left-to-right: +, -, *, /, %, &&, ||
• Right-to-left: =, +=, -=, *=, /=, %=, **
Example:
echo 10 - 5 + 2; // Evaluated left-to-right → (10 - 5) + 2 = 7
Relational (Comparison) Operators
Used to compare two values.
Operator Description Example
== Equal $a == $b
!= Not equal $a != $b
> Greater than $a > $b
< Less than $a < $b
>= Greater than or equal to $a >= $b
<= Less than or equal to $a <= $b
=== Identical (equal and same type) $a === $b
!== Not identical $a !== $b
Example:
$x = 10;
$y = 20;
if ($x < $y) {
echo "x is smaller";
}
Conditional Statements
Conditional statements are used to execute different code blocks based on
certain conditions.
The if Statement
Executes code if a condition is true.
if ($age >= 18) {
echo "You are eligible to vote.";
}
The else Statement
Executes an alternative block if the if condition is false.
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
The elseif Statement
Used to test multiple conditions.
if ($marks >= 75) {
echo "Distinction";
} elseif ($marks >= 50) {
echo "Pass";
} else {
echo "Fail";
}
The switch Statement
The switch statement executes code based on the value of a variable.
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week";
break;
case "Friday":
echo "End of the week";
break;
default:
echo "Midweek";
}
The Ternary (? :) Operator
A shorthand for simple if...else statements.
$age = 20;
$status = ($age >= 18) ? "Adult" : "Minor";
echo $status; // Output: Adult
Looping Statements
Loops execute a block of code repeatedly as long as a condition is true.
while Loop
Executes code while a condition is true.
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
do...while Loop
Executes code at least once, even if the condition is false.
$i = 1;
do {
echo $i;
$i++;
} while ($i <= 5);
for Loop
Used when the number of iterations is known.
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
Breaking Out of a Loop
The break statement immediately terminates the loop.
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) break;
echo $i;
}
The continue Statement
Skips the current iteration and continues with the next one.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) continue;
echo $i; // Output: 1 2 4 5
}
Summary
• Operators perform mathematical and logical operations.
• Precedence and associativity determine evaluation order.
• Conditional statements control decision-making.
• Loops repeat code efficiently.
• break exits loops early; continue skips an iteration.
Mastering these concepts helps in writing efficient, logical, and structured
PHP programs.