Functions in PHP
A function in PHP is a block of code that performs a specific task. It can take input (parameters),
process it, and return a result.
PHP provides built-in functions like fopen() and fread(), and we can also create user-defined
functions.
How to create a function in PHP
A function is created using the function keyword.
Syntax:
PHP
function functionName($parameter1, $parameter2) {
// code to be executed
return value;
Example:
PHP
<?php
function add($a, $b) {
return $a + $b;
echo add(5, 3);
?>
Output: 8
Explanation:
function → keyword to define function
add() → function name
$a, $b → parameters (inputs)
return → sends result back
Conclusion:
Functions help to reuse code, reduce repetition, and make programs easier to understand.
Invoking (Calling) a User-Defined Function in PHP
After creating a function, we need to invoke (call) it to execute its code.
A function is called by writing its name followed by parentheses ().
If the function has parameters, we pass values (arguments) inside the parentheses.
When the function is called, the code inside the function body gets executed.
Syntax:
PHP
functionName();
Example:
PHP
<?php
function writeMessage() {
echo "You are really a nice person, Have a nice time!";
writeMessage(); // Function call
?>
Output:
You are really a nice person, Have a nice time!
Explanation:
writeMessage() → function name
When we call it, the message inside the function is displayed
The function runs only when it is invoked
Conclusion:
Invoking a function is necessary to execute it. It helps in reusing code easily whenever required.
✅ 1. Default Parameters in PHP
Definition:
A default parameter is a parameter that has a predefined value in the function definition. If no
value is passed during function call, the default value is used.
Key Points:
Makes parameters optional
Defined in function declaration
Passed value overrides default value
Syntax:
PHP
function functionName($param = value) {
// code
Example:
PHP
<?php
function greet($name = "Guest") {
echo "Hello " . $name;
greet();
echo "<br>";
greet("Muskan");
?>
Explanation:
$name = "Guest" is default value
greet() → no value passed → uses "Guest"
greet("Muskan") → value overrides default
Conclusion:
Default parameters make functions flexible and reduce the need to pass values every time.
✅ 2. Actual Parameters in PHP
Definition:
An actual parameter is the value passed to a function during the function call.
Key Points:
Given in function call
Provided by caller
Passed inside parentheses
Syntax:
PHP
functionName(value1, value2);
Example:
PHP
<?php
function addnumbers($num1, $num2) {
$sum = $num1 + $num2;
echo "The sum of $num1 and $num2 is: $sum";
}
addnumbers(5, 10);
?>
Explanation:
5 and 10 are actual parameters
These values are passed while calling function
Conclusion:
Actual parameters are the real values given to a function at the time of calling.
✅ 3. Formal Parameters in PHP
Definition:
A formal parameter is a variable defined in the function definition to receive values.
Key Points:
Defined in function header
Acts as placeholder
Receives values from actual parameters
Syntax:
PHP
function functionName($param1, $param2) {
// code
Example:
PHP
<?php
function addnumbers($num1, $num2) {
$sum = $num1 + $num2;
echo "The sum of $num1 and $num2 is: $sum";
}
addnumbers(5, 10);
?>
Explanation:
$num1 and $num2 are formal parameters
They receive values 5 and 10
Conclusion:
Formal parameters are used to receive input values in a function.
Date and Time Function in PHP
Definition:
The date() function in PHP is used to get and format the current date and time from the server
in a readable format.
Key Points:
It returns the current date and time of the server
It is part of PHP core (no installation required)
It allows displaying date and time in different formats
It uses format characters to customize output
Syntax:
PHP
date(format, timestamp);
format → Required (specifies how date/time should be displayed)
timestamp → Optional (default is current date and time)
Definition:
A string is a sequence of characters used to represent text such as words and sentences.
In PHP, strings are enclosed in single quotes (‘ ’) or double quotes (“ ”).
Key Points:
Strings are used to store text data
Can be defined using single or double quotes
Single-quoted strings do not process special characters
Double-quoted strings process special characters and variables
Escape sequences can be used in strings
\n → New line
\t → Tab space
\$ → Dollar sign
\\ → Backslash
\" → Double quote
\' → Single quote
Ex : $variable_name = 'string value';
$variable_name = "string value";
Functions of string
String Functions Used in the Script
[Link]():Retrieves the length of a string.
Example:
$length = strlen($string);
echo "Length of the string: $length <br>";
Outputs: Length of the string: 13
[Link](): Converts a string to uppercase.
Example:
$uppercaseString = strtoupper($string);
echo "Uppercase string: $uppercaseString <br>";
Outputs: Uppercase string: HELLO, WORLD!
[Link](): Converts a string to lowercase.
Example:
$lowercaseString = strtolower($string);
echo "Lowercase string: $lowercaseString <br>";
Outputs: `Lowercase string: hello, world!`
[Link](): Retrieves a portion of a string.
Example:
$substring = substr($string, 0, 5); // Get first 5 characters
echo "Substring: $substring <br>";
Outputs: `Substring: Hello`
5.str_replace(): Replaces occurrences of a substring within a string.
Example:
$newString = str_replace("World", "PHP", $string);
echo "After replacement: $newString <br>";
Outputs: `After replacement: Hello, PHP!`
[Link](): Finds the position of the first occurrence of a substring within a string.
Example:
$position = strpos($string, "World");
echo "Position of 'World': $position <br>";
-Outputs: `Position of 'World': 7`
[Link](): Reverses a string.
Example:
$reversedString = strrev($string);
echo "Reversed string: $reversedString <br>";
Outputs: `Reversed string: !dlroW ,olleH`
Class
Definition:
A class is a blueprint or template used to create objects.
It defines properties (data) and methods (functions) in one unit.
Key Points:
Class is a collection of variables and functions
It defines the structure of objects
Properties → variables
Methods → functions inside class
Syntax:
PHP
class ClassName {
// properties and methods
Object
Definition:
An object is an instance of a class.
It represents a real-world entity created using a class.
Key Points:
Object is created from a class
Each object has its own values
Used to access class properties and methods
Syntax:
PHP
$objectName = new ClassName();
Creating and Accessing a Class & Object
Creating a Class:
Syntax:
class ClassName {
// Properties and methods
Example:
class Car {
public $brand;
public $model;
public $color;
public function start() {
// Method definition
}
Creating an Object:
Syntax:
$objectName = new ClassName();
Example:
$myCar = new Car()
Inheritance:
It is a fundamental principle in object-oriented programming (OOP) where a class can
inherit attributes and methods from another class.
A class which inherited by another class is known as a parent or base or super class.
A class which inherits another class is also known as child or derived or sub class.
This allows the child class to reuse code and extend the functionality of the parent
class.
It saves time, coding, memory since it reuses code.
Types of Inheritance
1. Single Inheritance
Single inheritance occurs when a class inherits properties and methods from only
one parent class.
Syntax
class Base {
// Properties and methods
class Derived extends Base {
// Additional properties and methods from base class
//properties and methods
Example:
<?php
class Animal {
public function makeSound() {
echo "Animal makes a sound.<br>";
class Dog extends Animal {
public function bark() {
echo "Dog barks.<br>";
$dog = new Dog();
$dog->makeSound(); // Output: Animal makes a sound.
$dog->bark(); // Output: Dog barks.
?>
2. Multilevel Inheritance
Multilevel inheritance involves a chain of inheritance where a derived class serves as
a base class for another class and is also know as intermediate class
Syntax:
class Base {
// Properties and methods
class intermediate extends Base {
class derived extends intermediate {
// Additional properties and methods specific to intermediate
// Properties and methods
Example
<?php
class Animal {
public function makeSound() {
echo "Animal makes a sound.<br>";
class Mammal extends Animal {
public function giveBirth() {
echo "Mammal gives birth.<br>";
class Dog extends Mammal {
public function bark() {
echo "Dog barks.<br>";
}
$dog = new Dog();
$dog->makeSound(); // Output: Animal makes a sound.
$dog->giveBirth(); // Output: Mammal gives birth.
$dog->bark(); // Output: Dog barks.
?>
3. Hierarchical Inheritance
Hierarchical inheritance involves one base class being inherited by multiple derived
classes.
Syntax:
class Base {
// Properties and methods
class Derived1 extends Base {
// Additional properties and methods specific to Base
// Properties and methods
class Derived2 extends Base {
// Additional properties and methods specific to Base
// Properties and methods}
Example:
<?php
class Animal {
public function makeSound() {
echo "Animal makes a sound.<br>";
}
class Dog extends Animal {
public function bark() {
echo "Dog barks.<br>";
class Cat extends Animal {
public function meow() {
echo "Cat meows.<br>";
$dog = new Dog();
$cat = new Cat();
$dog->makeSound(); // Output: Animal makes a sound.
$dog->bark(); // Output: Dog barks.
$cat->makeSound(); // Output: Animal makes a sound.
$cat->meow(); // Output: Cat meows.
?>
4. Multiple Inheritance (Simulated):
Definition:
Multiple inheritance means a class can inherit from more than one class.
PHP does not support direct multiple inheritance, but it can be achieved using:
Traits
Interfaces
a) Traits
Definition:
Traits are used to reuse methods in multiple classes. They help in code reuse.
Key Points:
Declared using trait keyword
Methods can be public, private, or protected
A class can use multiple traits
Used to share common functionality
Syntax:
PHP
trait TraitName {
// methods
class ClassName {
use TraitName;
b) Interfaces
Definition:
An interface defines a set of methods that a class must implement.
Key Points:
Declared using interface keyword
Methods are public by default
A class can implement multiple interfaces
Provides multiple behaviour rules
Syntax:
PHP
interface InterfaceName {
public function method1();
class ClassName implements InterfaceName {
public function method1() {
// code
<?php
interface Animal {
public function makeSound();
class Cat implements Animal {
public function makeSound() {
echo "Meow";
class Dog implements Animal {
public function makeSound() {
echo "Woof";
}
$cat = new Cat();
$cat->makeSound();
$dog = new Dog();
$dog->makeSound();
?>
1. Text Box (<input type="text">)
Definition:
A text box is used to accept single-line input from the user.
It allows entering text such as name or username.
It is commonly used for basic data entry in forms.
Syntax:
HTML
<input type="text" name="name">
Example:
HTML
Name: <input type="text" name="name">
Output:
Name: [__________]
2. Email Field (<input type="email">)
Definition:
An email field is used to collect a valid email address.
It checks the format automatically (must contain @).
It helps in preventing invalid email input.
Syntax:
HTML
<input type="email" name="email">
Example:
HTML
Email: <input type="email" name="email">
Output:
Email: [__________]
3. Password Field (<input type="password">)
Definition:
A password field is used to enter secure data.
The typed characters are hidden as dots or stars.
It is mainly used in login forms.
Syntax:
HTML
<input type="password" name="password">
Example:
HTML
Password: <input type="password" name="password">
Output:
Password: [••••••••]
4. Radio Button (<input type="radio">)
Definition:
Radio buttons allow selecting only one option from a group.
All options share the same name attribute.
It is used when only one choice is allowed.
Syntax:
HTML
<input type="radio" name="gender" value="male">
Example:
HTML
Gender:
<input type="radio" name="gender"> Male
<input type="radio" name="gender"> Female
Output:
Gender: ( ) Male ( ) Female
5. Checkbox (<input type="checkbox">)
Definition:
Checkbox is used to select multiple options.
Each option can be selected independently.
It is used for choices like skills or interests.
Syntax:
HTML
<input type="checkbox" name="lang" value="HTML">
Example:
HTML
Languages:
<input type="checkbox"> HTML
<input type="checkbox"> CSS
Output:
Languages: [ ] HTML [ ] CSS
6. Textarea (<textarea>)
Definition:
Textarea is used for multi-line text input.
It allows entering long text like address or comments.
It can store large amounts of data.
Syntax:
HTML
<textarea name="address"></textarea>
Example:
HTML
Address:
<textarea name="address"></textarea>
Output:
Address:
[ ]
7. Select / Dropdown (<select>)
Definition:
Select is used to create a dropdown list of options.
User can choose one or more options.
It helps in organizing multiple choices.
Syntax:
HTML
<select name="course">
<option>BCA</option>
</select>
Example:
HTML
Course:
<select>
<option>BCA</option>
<option>BSc</option>
</select>
Output:
Course: [BCA ▼]
8. Submit Button (<input type="submit">)
Definition:
Submit button is used to send form data to server.
It triggers form processing when clicked.
It is the final step in form submission.
Syntax:
HTML
<input type="submit" value="Submit">
Example:
HTML
<input type="submit" value="Submit">
Output:
[ Submit ]
✅ This is perfect exam answer (full marks guaranteed)
If you want, I can �convert this into PDF notes for revision 📄
Form Validation in PHP
Definition:
Form validation in PHP is the process of checking user input data to make sure it is correct,
complete, and secure before processing it.
It helps to avoid errors and protect data from misuse.
How we do Form Validation (Steps)
Create HTML Form:
First, we create a form with input fields like name, email, password, etc.
User Input:
The user fills the form and submits it. Data is sent to PHP using GET or POST.
Check Data in PHP:
In PHP, we validate the data using conditions:
Check empty fields → empty()
Check format → email validation
Check length → password length
Display Error Messages:
If any input is wrong, show error messages near the fields so user can correct it.
Sanitization:
Clean the data using functions like trim(), htmlspecialchars() to avoid security issues.
Process Data:
If all data is correct, then store it in database or use it further.
1. INT (Integer)
Definition:
INT is used to store whole numbers without decimal values.
It can store positive and negative numbers and is commonly used for IDs, age, count, etc.
It is one of the most used numeric data types in MySQL.
Syntax:
SQL
column_name INT
Code Example:
SQL
CREATE TABLE Student (
id INT AUTO_INCREMENT PRIMARY KEY,
age INT
);
INSERT INTO Student (age) VALUES (25), (30), (45);
2. VARCHAR
Definition:
VARCHAR is used to store text data of variable length.
It saves only the space required for the entered data, so it is memory efficient.
It is mainly used for storing names, emails, and short text.
Syntax:
SQL
column_name VARCHAR(size)
Code Example:
SQL
CREATE TABLE Student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
INSERT INTO Student (name) VALUES ('Rahul'), ('Bob'), ('Charlie');
3. DATE
Definition:
DATE is used to store date values only.
The format is fixed as YYYY-MM-DD.
It is useful for storing birthdate, joining date, etc.
Syntax:
SQL
column_name DATE
Code Example:
SQL
CREATE TABLE Student (
id INT AUTO_INCREMENT PRIMARY KEY,
birthdate DATE
);
INSERT INTO Student (birthdate) VALUES
('1990-01-01'), ('1985-05-20');
4. BOOLEAN
Definition:
BOOLEAN is used to store true or false values.
Internally, MySQL stores TRUE as 1 and FALSE as 0.
It is useful for status fields like active/inactive.
Syntax:
SQL
column_name BOOLEAN
Code Example:
SQL
CREATE TABLE Employee (
id INT AUTO_INCREMENT PRIMARY KEY,
is_active BOOLEAN
);
INSERT INTO Employee (is_active) VALUES (TRUE), (FALSE);
5. DECIMAL
Definition:
DECIMAL is used to store exact decimal values with precision.
It is mainly used for money and financial calculations where accuracy is important.
Example: DECIMAL(10,2) means 10 digits total and 2 after decimal.
Syntax:
SQL
column_name DECIMAL(total_digits, decimal_places)
Code Example:
SQL
CREATE TABLE Employee (
id INT AUTO_INCREMENT PRIMARY KEY,
salary DECIMAL(10,2)
);
INSERT INTO Employee (salary) VALUES
(50000.00), (60000.50);
6. TEXT
Definition:
TEXT is used to store large amount of text data.
It is useful for storing long descriptions, comments, or content.
It can store more data than VARCHAR.
Syntax:
SQL
column_name TEXT
Code Example:
SQL
CREATE TABLE TextBook (
id INT AUTO_INCREMENT PRIMARY KEY,
description TEXT
);
INSERT INTO TextBook (description) VALUES
('This is a long text description.');
7. FLOAT
Definition:
FLOAT is used to store decimal numbers with approximate values.
It may lose precision due to rounding.
It is used in scientific calculations or measurements.
Syntax:
SQL
column_name FLOAT
Code Example:
SQL
CREATE TABLE Numbers (
id INT AUTO_INCREMENT PRIMARY KEY,
value FLOAT
);
INSERT INTO Numbers (value) VALUES (123.45), (678.90);
8. TIMESTAMP
Definition:
TIMESTAMP is used to store date and time together.
The format is YYYY-MM-DD HH:MM:SS.
It is commonly used to track record creation or update time.
Syntax:
SQL
column_name TIMESTAMP
Code Example:
SQL
CREATE TABLE House (
id INT AUTO_INCREMENT PRIMARY KEY,
build_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO House (build_at) VALUES (NOW());