Hassan S. PHP Programming For Beginners. A Quick Start Guide... 2024hassan S. PHP Programming For Beginners. A Quick Start Guide... 2024
Hassan S. PHP Programming For Beginners. A Quick Start Guide... 2024hassan S. PHP Programming For Beginners. A Quick Start Guide... 2024
First Edition
Sarful Hassan
Preface
Welcome to PHP Programming for Beginners! This
book is designed to be a comprehensive and
accessible guide to PHP, one of the most popular
server-side scripting languages for web development.
Whether you’re a complete novice to programming or
looking to add PHP to your skillset, this book aims to
provide a clear, step-by-step introduction to building
dynamic web applications using PHP.
Who This Book Is For
This book is intended for absolute beginners in
programming who want to learn PHP. If you have a
basic understanding of HTML and want to enhance
your web development skills by learning server-side
scripting, this book is perfect for you. It is also
suitable for developers from other languages who
want to get a quick start with PHP.
How This Book Is Organized
The book is divided into well-structured chapters,
each focusing on a specific aspect of PHP
programming:
Chapter 1-5 cover the basics of PHP,
including installation, variables, constants,
and data types.
Chapters 6-10 focus on operators, control
structures, and handling strings and arrays.
Chapters 11-15 delve into functions,
variable scope, superglobals, and file
handling.
Chapters 16-20 explore advanced topics
like sessions, cookies, object-oriented
programming (OOP), error handling, and
basic database interaction with MySQL.
Release Notes
This first edition covers PHP 8.0 and higher. It
introduces new features and improvements in PHP,
including enhanced error handling, improved type
safety, and new syntax updates, ensuring you learn
the most up-to-date version of the language.
Notes on the First Edition
This book has been carefully curated with beginners
in mind, focusing on fundamental concepts and
practical examples. Feedback and suggestions are
always welcome to help improve future editions.
MechatronicsLAB Online Learning
For additional resources, tutorials, and exercises, visit
MechatronicsLAB's online learning platform. Enhance
your learning experience with interactive content and
video tutorials tailored to complement this book.
How to Contact Us
We love hearing from our readers! If you have any
questions, feedback, or suggestions, feel free to
reach out to us:
Email: [email protected]
Website: mechatronicslab.net
PHP Introduction
What is PHP?
PHP (Hypertext Preprocessor) is a server-side, open-
source, and scripting language primarily used for web
development. PHP is embedded into HTML, allowing for
dynamic web page content creation and efficient server-side
programming.
Why Use PHP?
1. Web Integration:
2. Database Connectivity:
3. Server-Side Scripting:
4. Cross-Platform:
○ PHP is platform-independent, running on
Windows, Linux, macOS, and more, making it
highly versatile.
4. Session Management:
3. API Development:
4. E-commerce Applications:
2. Install PHP:
○
Follow the instructions for your OS:
■ Windows: Run the installer or
download the ZIP file, extract it, and add
the PHP directory to your PATH.
Linux: Use the following commands to install PHP:
3. Verify Installation:
Open a terminal and type:
php -v
○ You should see the installed PHP version.
Step 2: Install a Web Server (e.g., Apache)
1. Install Apache (Linux/Windows):
Linux:
sudo apt install apache2
○
Start the Apache service and navigate to
http://localhost in a browser.
Step 3: Create a PHP Script and Run It
○
Open a text editor and create a file named
hello.php .
Write the Following Code:
<?php
echo "Hello, PHP!";
?>
PHP Syntax
What is PHP Syntax?
PHP syntax refers to the rules and structure for writing
PHP code, focusing on embedding PHP within HTML and
dynamic content generation.
Why is PHP Syntax Important?
● Ensures Consistency: Proper syntax ensures
readable and maintainable code.
● Prevents Errors: Following syntax rules helps
avoid runtime errors.
● Enables Web Integration: PHP syntax allows easy
embedding of PHP code within HTML, making web
development seamless.
Basic Syntax Rules
Example
<?php
function greet($name) {
echo "Hello, " . $name . "!";
}
greet("Alice");
?>
Output Result
Hello, Alice!
Explanation of Rules
Rule Example Explanation
Use
Opening <?php PHP code is enclosed within the
Tag echo "Hi"; <?php ... ?> tags.
?>
PHP Output
What is PHP Output?
PHP output refers to displaying information or results using
functions like echo , print , or HTML embedding.
Types of Output in PHP
<?php
echo "Hello, World!";
?>
Variable Output:
<?php
$age = 25;
echo $age;
?>
Combined Output:
<?php
$name = "Alice";
echo "Name: " . $name;
?>
Output Result
Hello, World!
25
Name: Alice
Explanation
● Text Output:
○ Prints a static string to the web page.
● Variable Output:
○ Prints the value of a variable to the web
page.
● Combined Output:
○ Combines text and variable values in a
single output statement using concatenation.
PHP Comments
What are PHP Comments?
PHP comments are lines of code ignored by the
interpreter. They are used to describe code, clarify logic,
or disable specific code lines temporarily.
Why are PHP Comments Important?
● Improves Code Readability:
○ Makes code easier to understand.
● Facilitates Maintenance:
○ Helps in modifying and updating code.
● Provides Documentation:
○ Used to explain functions, variables, and
logic.
Types of Comments in PHP
Seria Type Syntax Purpose
l No
1 Single // Used for short
-line comment explanations.
2 Single # Alternative for single-line
-line comment comments.
Multi-line Comment:
<?php
/* This is a multi-line comment
explaining the following code block */
$age = 18;
?>
Output Result
● Comments do not produce any output as they are
meant for clarification within the code.
Explanation
● Single-line Comment:
○ Used for brief notes or explanations to
improve code clarity.
● Multi-line Comment:
○ Used for longer explanations or to disable
multiple lines of code.
1. PHP Variables
What are PHP Variables
Variables in PHP are containers that hold data values,
enabling dynamic data management. They are essential for
storing, processing, and manipulating data, such as user
input, calculations, or dynamic content.
Use Purpose
● Store dynamic data, including strings, numbers,
arrays, and objects, which may change during
execution.
● Facilitate data manipulation, enabling
mathematical operations, string processing, or logical
evaluations.
● Organize information, making code more
readable, maintainable, and easier to debug.
● Enable user interaction, storing inputs,
processing results, and displaying outputs
dynamically.
Syntax
$variable_name = value;
Syntax Explanation
● $:
○ The dollar sign is mandatory for declaring
variables in PHP. It identifies a variable within
the code.
● variable_name :
○ The variable name can include letters,
numbers, and underscores but must start with
a letter or an underscore. It should be
descriptive to indicate its purpose.
● value :
○ The value can be a string, integer, float,
array, boolean, or even an object, representing
the data held by the variable.
Simple Code Example
<?php
$age = 25; // Integer variable
$name = "Alice"; // String variable
Notes
● Variables in PHP are dynamically typed,
meaning the type can change based on the assigned
value.
● Variable names are case-sensitive, making $age
different from $Age or $AGE .
● Variable names should be descriptive, indicating
the kind of data they hold (e.g., $user_name ,
$total_amount ).
Warnings
● Avoid using PHP reserved keywords as variable
names (e.g., $class , $function ).
● Always initialize variables before using them to
avoid warnings or errors.
● Using undeclared variables can generate Notices,
which may affect debugging or error handling.
2. String Variables
What are String Variables
String variables store sequences of characters, such as
words, sentences, or any textual data. They are used to
manage, manipulate, and display textual information in PHP
applications.
Use Purpose
● Store and display text, such as user inputs,
messages, descriptions, or HTML content.
● Perform string operations, including
concatenation, searching, replacing, and slicing.
● Manage text-based data effectively in web
applications, such as form inputs, URLs, and JSON
strings.
Syntax
$variable_name = "string";
Syntax Explanation
● "string" :
○ Text enclosed in double quotes is treated as a
string in PHP. Single quotes can also be used,
but they do not allow variable interpolation
(e.g., "Hello, $name" ).
Simple Code Example
<?php
$greeting = "Hello, World!";
$custom_message = "Welcome, $name!";
echo $greeting; // Outputs: Hello, World!
?>
Notes
● Double-quoted strings allow variable
interpolation, enabling dynamic string creation.
● Single-quoted strings treat the content literally,
which is useful for performance when no interpolation
is needed.
● String concatenation uses the dot operator ( . ) to
join multiple strings.
Warnings
● Ensure proper use of quotes to avoid syntax errors,
especially when mixing single and double quotes.
● Use escape characters ( \ ) to include special
characters within strings (e.g., \" for double quotes).
3. Integer Variables
What are Integer Variables
Integer variables store whole numbers without decimals.
They can be positive, negative, or zero. Integers are widely
used for arithmetic operations, counting, indexing, and
logical evaluations.
Use Purpose
● Store numeric values like age, count, score, or IDs
for calculations.
● Perform arithmetic operations, such as addition,
subtraction, multiplication, and division.
● Use as loop counters, indexes for arrays, or flags
in conditional statements.
Syntax
$variable_name = integer;
Syntax Explanation
● integer :
○ Represents a whole number, such as 0, -10,
25, or 100, without decimal points.
Simple Code Example
<?php
$count = 10; // Integer variable
$sum = $count + 5;
echo $sum; // Outputs: 15
?>
Notes
● PHP supports basic arithmetic operations,
making it easy to perform calculations with integers.
● Integer variables are commonly used in loops,
conditional statements, and array indexing.
● PHP automatically converts numeric strings to
integers when performing arithmetic operations.
Warnings
● Be cautious of division by zero, as it will generate a
warning or error.
● Always use parentheses to ensure the correct order
of operations in complex expressions.
4. PHP Constants
What are PHP Constants
Constants are immutable values that do not change during
the execution of a program. They are defined using the
define() function or the const keyword, providing a reliable
way to store fixed values.
Use Purpose
● Store fixed values, such as configuration settings,
mathematical constants (e.g., PI), or API keys.
● Ensure data integrity, preventing accidental
changes to critical values throughout the code.
● Improve code readability, making it clear that
certain values should remain constant.
Syntax
define("CONSTANT_NAME", value);
Syntax Explanation
● define() :
○ A function used to define a constant. The first
argument is the constant's name (typically
uppercase), and the second argument is its
value.
● CONSTANT_NAME :
○
The name of the constant, which is usually
written in uppercase to differentiate it from
variables.
Simple Code Example
<?php
define("PI", 3.14);
echo PI; // Outputs: 3.14
?>
Notes
● Constants are accessible globally throughout the
code once defined.
● Use uppercase for constant names to distinguish
them from variables.
● Constants cannot be changed or unset after
being defined.
Warnings
● Do not use constants for values that may need to
change during execution.
● Constants are defined globally, so be mindful of
naming conflicts.
5. Const Keyword
What is the Const Keyword
The const keyword is another way to define constants in
PHP, typically used within classes for object-oriented
programming. It provides a straightforward way to create
unchangeable values.
Use Purpose
● Define constants in object-oriented programming,
providing consistent values within classes.
● Create global constants, serving as an alternative
to the define() function.
● Maintain code structure, ensuring values remain
unchanged throughout the program.
Syntax
const CONSTANT_NAME = value;
Syntax Explanation
● const CONSTANT_NAME = value; :
○ Declares a constant with the specified name
and value. It can be used globally or within a
class but not inside functions or conditional
blocks.
Simple Code Example
<?php
class Circle {
const PI = 3.14;
}
6. Using Constants
What is Using Constants
Constants, once defined, can be accessed like variables but
without the $ symbol. They provide stability and
predictability by ensuring fixed values are used throughout
the program.
Use Purpose
● Access unchangeable values in the program,
maintaining consistency and reliability.
● Use for configuration settings, such as database
credentials, file paths, or API endpoints.
● Enhance code readability, making it clear which
values are constant and should not be modified.
Syntax
echo CONSTANT_NAME;
Syntax Explanation
● CONSTANT_NAME :
○ The name of the constant is used directly
(without $ ) to access its value.
Simple Code Example
<?php
define("SITE_NAME", "My Website");
echo SITE_NAME; // Outputs: My Website
?>
Notes
● Constants are useful for storing global settings,
like site names, version numbers, or API limits.
● Once defined, constants are accessible from any
part of the program without re-declaration.
Warnings
● Constants are global, so be mindful of potential
naming conflicts, especially in large applications.
● Ensure that constant values are accurately set at
the start, as they cannot be changed later.
Final Project: "Website Configuration Manager"
Project Goal
● Create a PHP script that uses both variables and
constants to manage website settings.
● Demonstrate the declaration, initialization, and
usage of variables and constants in practical
scenarios.
Code for This Project
<?php
// Define constants for website settings
define("SITE_NAME", "My PHP Site");
define("MAX_USERS", 100);
const VERSION = "1.0";
Syntax Table
Seri Data Syntax Simple Example
al Type
No
1 String $variable = $name = "Alice";
"string";
2 Integer $variable = $age = 25;
integer;
3 Float $variable = float; $price = 99.99;
4 Boolea $variable = $is_valid = true;
n true/false;
5 Array $variable = $colors =
array(values); array("red",
"green");
6 NULL $variable = null; $no_value = null;
$variable = "string";
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating it is a
variable.
○ The variable name can contain letters,
numbers, and underscores but must start with
a letter or an underscore.
● "string" :
○ A sequence of characters enclosed in double
quotes. Double quotes allow variable
interpolation, where variables within the string
are replaced with their values.
○ Single quotes ( 'string' ) can also be used for
strings but do not support variable
interpolation, treating everything inside as
plain text.
● String concatenation:
○ In PHP, you concatenate strings using the dot
operator ( . ). This allows combining multiple
strings into one.
Simple Code Example
<?php
$greeting = "Hello";
$name = "Alice";
$full_greeting = $greeting . ", " . $name . "!";
echo $full_greeting; // Outputs: Hello, Alice!
?>
Notes
● Double-quoted strings allow for variable
interpolation, making them useful for dynamic
strings.
● Use single-quoted strings for literal strings or when
performance is a concern, as PHP processes them
faster than double-quoted strings.
Warnings
● Use escape characters ( \ ) to handle special
characters, like \" for double quotes inside a double-
quoted string.
● Be aware of accidental concatenation errors when
using multiple dot operators.
$variable = integer;
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating a
variable.
○
The variable name follows the same naming
rules as for other data types.
● integer :
○ Represents a whole number, which can be
positive (e.g., 25 ), negative (e.g., -10 ), or
zero ( 0 ).
○ Integers in PHP do not require special
notation and are automatically recognized
when assigned.
○ When performing arithmetic operations, PHP
converts numeric strings to integers if they
contain valid whole numbers.
Simple Code Example
<?php
$count = 10;
$items = 5;
$total = $count + $items; // Addition
echo $total; // Outputs: 15
?>
Notes
● PHP supports various arithmetic operators, including
+ (addition), - (subtraction), * (multiplication), /
(division), and % (modulus).
● PHP converts numeric strings to integers
automatically when they are used in arithmetic
operations.
Warnings
● Dividing by zero generates a warning and can
disrupt execution.
● Use parentheses to ensure the correct order of
operations in complex expressions, following standard
mathematical rules (e.g., PEMDAS).
3. Float Data Type
What is the Float Data Type
The float data type represents numbers with decimal points,
also known as floating-point numbers. Floats are used for
precise calculations involving fractions, financial values, and
measurements.
Use Purpose
● Store decimal values, such as prices, scores, or
measurements.
● Perform arithmetic operations that require
decimal precision, like calculations involving
percentages or averages.
● Handle fractions and ratios, making them
suitable for scientific or financial computations.
Syntax
$variable = float;
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating a
variable.
● float :
○ Represents a number with a decimal point,
like 3.14 , -1.5 , or 99.99 .
○ Floats can be written with or without leading
zeros ( .5 or 0.5 ).
○ Floats are automatically recognized when a
decimal point is included in the value
assignment.
Simple Code Example
<?php
$price = 99.99;
$tax = 0.08;
$total = $price + ($price * $tax); // Total calculation with tax
echo $total; // Outputs: 107.99
?>
Notes
● PHP supports floating-point arithmetic, but be aware
of potential rounding errors due to the way floats are
stored in memory.
● Use built-in functions like round() , ceil() , or floor()
to manage decimal precision as needed.
Warnings
● Comparing floats directly for equality can lead to
inaccurate results due to floating-point
representation.
● Use functions like bccomp() for precise float
comparisons in critical calculations, such as financial
transactions.
4. Boolean Data Type
What is the Boolean Data Type
The boolean data type represents two possible values: true
or false . Booleans are used in conditional statements to
control program flow and manage logical operations.
Use Purpose
● Control conditional statements, such as if-else
structures and loops.
● Store binary states, like yes/no, on/off, or
enabled/disabled.
● Perform logical operations, ensuring specific
conditions are met.
Syntax
$variable = true/false;
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating a
variable.
● true or false :
○ Represents logical truth or falsehood in PHP.
○ Booleans do not require quotation marks, as
they are keywords.
○ PHP evaluates various data types as
booleans: non-zero numbers, non-empty
strings, and arrays with elements are
considered true , while 0 , empty strings ( "" ),
empty arrays ( array() ), and null are
considered false .
Simple Code Example
<?php
$is_logged_in = true;
if ($is_logged_in) {
echo "User is logged in.";
} else {
echo "User is not logged in.";
}
?>
Notes
● Booleans are often used in loops and conditional
statements to manage program flow.
● Use strict comparison ( === ) to ensure the boolean
data type matches during evaluation.
Warnings
● Type coercion in PHP can lead to unexpected results
when using loose comparison ( == ), as PHP attempts
to convert values to booleans during evaluation.
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating a
variable.
● array() :
○ A built-in PHP function that creates an array,
capable of holding a collection of values.
● Values within an array:
○ Each value can be of a different data type,
including strings, integers, floats, booleans, or
even other arrays.
○ Arrays can be created using the [] syntax for
shorthand (e.g., $variable = [value1,
value2]; ).
Simple Code Example
<?php
$fruits = array("apple", "banana", "cherry");
$colors = ["red", "green", "blue"]; // Shorthand syntax
echo $fruits[1]; // Outputs: banana
?>
Notes
● PHP supports associative arrays, where elements are
accessed by keys instead of indexes (e.g.,
array("name" => "Alice") ).
● Arrays can be multi-dimensional, containing arrays
within arrays.
Warnings
● Ensure that keys exist before accessing array
elements to avoid undefined index errors.
● When using large arrays, consider memory usage
and performance implications.
Syntax Explanation
● $variable :
○ Begins with a $ symbol, indicating a
variable.
● null :
○ A special keyword that represents the
absence of a value. It is not case-sensitive, so
NULL or Null is also valid.
<?php
$no_value = null;
if (is_null($no_value)) {
echo "Variable has no value.";
}
?>
Notes
● Use is_null() to check if a variable is NULL, ensuring
proper handling of empty values.
● Variables set to NULL can be redefined with new
values later.
Warnings
● Be cautious when using NULL in conditions, as it can
produce unexpected results if not handled correctly.
● Avoid using NULL for variables that are expected to
hold valid data during execution.
Syntax
Syntax Explanation
●
$variable :
○ Begins with a $ symbol, indicating a
variable.
● new ClassName() :
○ Creates a new object instance of the specified
class.
○ The new keyword allocates memory for the
object and initializes it based on the class
definition.
○ Objects can have properties (variables) and
methods (functions) defined within the class.
Simple Code Example
<?php
class Car {
public $make;
public $model;
<?php
// User information
$name = "Alice Johnson"; // String
$age = 28; // Integer
$is_active = true; // Boolean
$favorite_fruits = array("apple", "banana", "cherry"); // Array
$height = 5.5; // Float
$nickname = null; // NULL
2 Subtraction $a - $b $a = 5; $b $c = 2;
= 3; $c =
$a - $b;
3 Multiplication $a * $b $a = 5; $b $c =
= 3; $c = 15;
$a * $b;
4 Division $a / $b $a = 10; $b $c = 5;
= 2; $c =
$a / $b;
5 Modulus $a % $a = 5; $b $c = 1;
$b = 2; $c =
$a % $b;
6 Exponentiation $a ** $a = 2; $b $c = 8;
$b = 3; $c =
$a ** $b;
1. Addition Operator ( + )
What is the Addition Operator
The addition operator ( + ) is used to add two numbers. It is
one of the basic arithmetic operators and is used to perform
simple mathematical addition.
Use Purpose
● Add two numbers, whether integers or floats.
● Increase values dynamically, such as adding
quantities or totals.
● Combine numeric results for summing arrays or
values in loops.
Syntax
$result = $a + $b;
Syntax Explanation
● $a and $b :
○ Variables holding numeric values that are
being added together. PHP supports adding
integers and floats directly.
● +:
○ The addition operator performs the addition
operation between two operands.
● $result :
○ The variable stores the result of the addition,
which is the sum of $a and $b .
Simple Code Example
<?php
$a = 10;
$b = 20;
$sum = $a + $b;
echo "The sum is: " . $sum; // Outputs: The sum is: 30
?>
Notes
● PHP automatically converts numeric strings to
numbers when using the addition operator (e.g., "5"
+ 10 results in 15 ).
● Addition can be used within loops to calculate
running totals or aggregates.
Warnings
● Adding non-numeric strings results in a warning and
returns 0.
● Be aware of type conversion issues when using
addition with mixed data types.
2. Subtraction Operator ( - )
What is the Subtraction Operator
The subtraction operator ( - ) is used to subtract one number
from another. It allows for mathematical operations that
decrease or deduct values.
Use Purpose
● Subtract numbers, such as calculating differences
or reducing values.
● Calculate changes in values, like finding the
difference between two quantities.
● Use in loops or conditions to decrement counters
or values.
Syntax
$result = $a - $b;
Syntax Explanation
● $a and $b :
○ Variables containing numeric values. The
value of $b is subtracted from $a .
● -:
○ The subtraction operator reduces the value of
$a by $b .
● $result :
○ Stores the difference between $a and $b .
Simple Code Example
<?php
$a = 15;
$b = 5;
$difference = $a - $b;
echo "The difference is: " . $difference; // Outputs: The difference is: 10
?>
Notes
● PHP supports subtraction for both integers and
floats.
● Subtraction is commonly used in loops, counters,
and calculations of differences.
Warnings
● Subtracting from non-numeric strings results in a
warning and returns 0.
● Be cautious with negative results, as they can affect
conditions and calculations.
3. Multiplication Operator ( * )
What is the Multiplication Operator
The multiplication operator ( * ) multiplies two numbers. It is
used to perform calculations that require repeated addition.
Use Purpose
● Multiply numbers for scaling values or calculating
areas, volumes, etc.
● Increase values by a factor, such as calculating
prices, totals, or quantities.
● Perform mathematical calculations, like finding
products of arrays or loops.
Syntax
$result = $a * $b;
Syntax Explanation
● $a and $b :
○ Variables containing numeric values that will
be multiplied.
● *:
○The multiplication operator calculates the
product of $a and $b .
● $result :
○ Stores the product of $a and $b .
Simple Code Example
<?php
$a = 4;
$b = 5;
$product = $a * $b;
echo "The product is: " . $product; // Outputs: The product is: 20
?>
Notes
● Multiplication is useful in loops for scaling, totals,
and more complex calculations.
● PHP automatically converts numeric strings to
numbers when multiplying.
Warnings
● Multiplying non-numeric strings returns 0.
● Be aware of potential overflow issues when
multiplying large integers.
4. Division Operator ( / )
What is the Division Operator
The division operator ( / ) divides one number by another. It
is used to split values into smaller parts or to find ratios.
Use Purpose
● Divide values, such as splitting amounts,
calculating averages, or distributing items.
● Calculate ratios or proportions between numbers.
● Perform mathematical operations, like
calculating per-unit costs.
Syntax
$result = $a / $b;
Syntax Explanation
● $a and $b :
○ Variables containing numeric values. $a is
divided by $b .
● /:
○ The division operator calculates the quotient
of $a and $b .
● $result :
○ Stores the quotient of the division.
Simple Code Example
<?php
$a = 20;
$b = 4;
$quotient = $a / $b;
echo "The quotient is: " . $quotient; // Outputs: The quotient is: 5
?>
Notes
● Division results in a float if the result is not a whole
number (e.g., 5 / 2 results in 2.5 ).
● Use the division operator in loops, conditions, and
calculations that involve splitting values.
Warnings
● Division by zero results in a warning or error,
disrupting execution.
● Ensure that the divisor ( $b ) is not zero before
performing division.
5. Modulus Operator ( % )
What is the Modulus Operator
The modulus operator ( % ) returns the remainder of a
division. It is commonly used to determine if a number is
even or odd or to cycle through repeated patterns.
Use Purpose
● Find remainders, such as when dividing items
evenly.
● Check if a number is even or odd( $num % 2 ).
● Cycle through patterns, like alternating colors,
rows, or elements in arrays.
Syntax
$result = $a % $b;
Syntax Explanation
● $a and $b :
○ Variables containing numeric values. $a is
divided by $b , and the remainder is returned.
● %:
○ The modulus operator calculates the
remainder of $a divided by $b .
● $result :
○ Stores the remainder of the division.
Simple Code Example
<?php
$a = 10;
$b = 3;
$remainder = $a % $b;
echo "The remainder is: " . $remainder; // Outputs: The remainder is: 1
?>
Notes
● The modulus operator is often used to determine if a
number is evenly divisible by another number.
● It is also useful for looping patterns, such as
alternating rows or actions.
Warnings
● Using the modulus operator with non-integer
operands can yield unexpected results.
● Ensure that the divisor ( $b ) is not zero, as it will
generate a division-by-zero error.
6. Exponentiation Operator ( ** )
What is the Exponentiation Operator
The exponentiation operator ( ** ) raises one number to the
power of another. It is used for mathematical calculations
that involve powers, such as squares, cubes, or higher
powers.
Use Purpose
● Calculate powers, like squares, cubes, or
exponential growth.
● Perform complex calculations, such as
calculating growth rates or scientific computations.
● Handle mathematical operations, like raising
numbers to specific powers.
Syntax
$result = $a ** $b;
Syntax Explanation
● $a and $b :
○ Variables containing numeric values. $a is
raised to the power of $b .
● ** :
○ The exponentiation operator calculates the
result of $a raised to the power of $b .
● $result :
○ Stores the result of the exponentiation.
Simple Code Example
<?php
$a = 2;
$b = 3;
$power = $a ** $b;
echo "The result is: " . $power; // Outputs: The result is: 8
?>
Notes
● The exponentiation operator is useful in financial
calculations (e.g., compound interest) and scientific
computations.
● PHP supports floating-point values in both the base
and the exponent.
Warnings
● Be aware of overflow or underflow when using large
numbers with exponentiation.
Final Project: "Basic Calculator"
Project Goal
●Create a PHP script that uses arithmetic operators to
perform basic calculations (addition, subtraction,
multiplication, division, modulus, and
exponentiation).
● Demonstrate user input handling and arithmetic
operations.
Code for This Project
<?php
// Define two numbers
$num1 = 10;
$num2 = 5;
// Perform calculations
$sum = $num1 + $num2;
$difference = $num1 - $num2;
$product = $num1 * $num2;
$quotient = $num1 / $num2;
$remainder = $num1 % $num2;
$power = $num1 ** $num2;
// Display results
echo "Numbers: $num1 and $num2<br>";
echo "Addition: $sum<br>";
echo "Subtraction: $difference<br>";
echo "Multiplication: $product<br>";
echo "Division: $quotient<br>";
echo "Modulus: $remainder<br>";
echo "Exponentiation: $power<br>";
?>
Save and Run
● Save the code as calculator.php .
● Run it on a PHP server or use an online PHP
sandbox.
Check Output
The script will display the results of basic arithmetic
operations performed on the two numbers.
Summary
This chapter provided a comprehensive overview of PHP
arithmetic operators, covering addition, subtraction,
multiplication, division, modulus, and exponentiation. The
chapter concluded with a basic calculator project that
demonstrated how to use arithmetic operators for numerical
data manipulation in PHP.
Chapter-5 PHP Assignment Operators
Chapter Overview
This chapter covers PHP assignment operators, which are
used to assign values to variables. Assignment operators
provide a way to update variable values, combining
assignment with arithmetic or bitwise operations.
Chapter Goal
● Understand the various assignment operators
available in PHP.
● Learn how to use assignment operators to
manipulate variable values efficiently.
● Explore examples demonstrating different types of
assignment operators.
● Implement a project that utilizes assignment
operators for updating and managing data.
2 Addition $a += $a = 5; $a $a = 8;
Assignment $b += 3;
3 Subtraction $a -= $a = 5; $a $a = 2;
Assignment $b -= 3;
4 Multiplication $a *= $a = 5; $a $a = 15;
Assignment $b *= 3;
5 Division $a /= $a = 10; $a = 5;
Assignment $b $a /= 2;
6 Modulus $a %= $a = 5; $a $a = 1;
Assignment $b %= 2;
7 Exponentiation $a **= $a = 2; $a $a = 8;
Assignment $b **= 3;
8 Concatenation $a .= $a = $a =
Assignment $b "Hello"; $a "Hello
.= " World";
World";
$variable = value;
Syntax Explanation
● $variable :
○ The variable name, which begins with a $
symbol, indicating it is a variable.
● =:
○ The assignment operator assigns the value
on the right side to the variable on the left.
● value :
○ The value assigned to the variable, which can
be a string, number, boolean, array, or other
data type.
Simple Code Example
<?php
$age = 25;
$name = "Alice";
echo "Name: " . $name . ", Age: " . $age; // Outputs: Name: Alice, Age: 25
?>
Notes
● The simple assignment operator is used to set or
update variable values.
● PHP allows assigning values of different data types,
including strings, integers, floats, booleans, arrays,
and objects.
Warnings
● Ensure that the assigned value matches the
expected data type, as PHP converts data types
automatically.
● Assigning values to undeclared variables is allowed,
but it can cause warnings if error reporting is enabled.
$variable += value;
Syntax Explanation
● $variable :
○ The variable to which the value will be added
and assigned.
● += :
○ The addition assignment operator, which
adds the right-hand value to the variable and
updates the variable with the new value.
● value :
○ The value to be added to the existing
variable.
Simple Code Example
<?php
$total = 10;
$total += 5;
echo "Total: " . $total; // Outputs: Total: 15
?>
Notes
● The addition assignment operator is often used in
loops to accumulate totals or increment counters.
● PHP automatically converts numeric strings to
numbers when using the addition assignment
operator.
Warnings
● Ensure that the variable contains a numeric value
before using += to avoid unexpected results.
● Be cautious of using the operator with strings, as it
may lead to type conversion issues.
<?php
$balance = 100;
$balance -= 20;
echo "Remaining Balance: " . $balance; // Outputs: Remaining Balance: 80
?>
Notes
● The subtraction assignment operator is commonly
used to reduce counters, balances, or quantities.
● PHP supports subtraction for both integers and
floats.
Warnings
● Ensure that the variable contains a numeric value
before using -= to prevent unexpected results.
● Be cautious of subtracting from strings, as it may
cause type conversion errors.
$variable *= value;
Syntax Explanation
● $variable :
○ The variable to be multiplied and updated.
● *= :
○ The multiplication assignment operator,
which multiplies the variable by the right-hand
value and updates it.
● value :
○ The value to multiply with the existing
variable.
Simple Code Example
<?php
$price = 20;
$price *= 2;
echo "New Price: " . $price; // Outputs: New Price: 40
?>
Notes
● The multiplication assignment operator is useful for
scaling values, such as doubling prices or quantities.
● PHP converts numeric strings to numbers
automatically during multiplication.
Warnings
● Ensure that the variable contains a numeric value
before using *= to avoid unexpected behavior.
● Be aware of overflow when multiplying large
integers.
Use Purpose
● Divide values, such as calculating averages or
distributing quantities.
● Adjust values, such as scaling down or finding per-
unit costs.
● Use in loops or conditions to iteratively divide
values.
Syntax
$variable /= value;
Syntax Explanation
● $variable :
○ The variable to be divided and updated.
● /= :
○
The division assignment operator, which
divides the variable by the right-hand value
and updates it.
● value :
○ The value to divide the existing variable by.
Simple Code Example
<?php
$total = 100;
$total /= 4;
echo "Per Unit: " . $total; // Outputs: Per Unit: 25
?>
Notes
●The division assignment operator is often used to
distribute values or calculate averages.
● PHP converts numeric strings to floats automatically
during division if the result is not a whole number.
Warnings
● Ensure that the divisor is not zero, as dividing by
zero causes a warning or error.
● Be aware of float results when dividing integers, as
the result can be a float.
Syntax Explanation
● $variable :
○ The variable to which the modulus operation
is applied.
● %= :
○ The modulus assignment operator, which
calculates the remainder of dividing the
variable by the right-hand value and updates
it.
● value :
○ The value used to divide the existing
variable.
Simple Code Example
<?php
$num = 10;
$num %= 3;
echo "Remainder: " . $num; // Outputs: Remainder: 1
?>
Notes
● The modulus assignment operator is useful for
determining even or odd numbers or cycling patterns.
● Use it in loops to handle repeating patterns or
conditions.
Warnings
● Ensure that the divisor is not zero, as it will generate
a division-by-zero error.
● Use with integers, as modulus operations with non-
integers can yield unexpected results.
Syntax Explanation
● $variable :
○ The variable to be raised to a power and
updated.
● **= :
○ The exponentiation assignment operator,
which raises the variable to the power of the
right-hand value and updates it.
● value :
○ The power to raise the existing variable by.
Simple Code Example
<?php
$num = 2;
$num **= 3;
echo "Result: " . $num; // Outputs: Result: 8
?>
Notes
● The exponentiation assignment operator is useful for
calculating powers in scientific, financial, or statistical
calculations.
● PHP supports floating-point values in both the base
and the exponent.
Warnings
● Be cautious of overflow or underflow when using
large numbers with exponentiation.
● Exponentiation can consume significant memory
and processing time with large exponents.
$variable .= value;
Syntax Explanation
● $variable :
○ The string variable to which another string
will be appended.
● .= :
○ The concatenation assignment operator,
which appends the right-hand string to the
variable and updates it.
● value :
○ The string to append to the existing variable.
<?php
$message = "Hello";
$message .= " World";
echo $message; // Outputs: Hello World
?>
Notes
● The concatenation assignment operator is
commonly used to build longer strings from smaller
parts.
● It is useful in loops or when constructing dynamic
content, like HTML, logs, or messages.
Warnings
● Ensure that the variable contains a string before
using .= to avoid type conversion issues.
● Be cautious of appending large strings, as it can
affect memory usage and performance.
Final Project: "Shopping Cart Manager"
Project Goal
● Create a PHP script that uses assignment operators
to manage a simple shopping cart.
● Implement calculations for total price, discounts,
and item quantities.
Code for This Project
<?php
// Initial values
$item_price = 50;
$quantity = 2;
$discount = 10; // In percent
// Apply discount
$total -= ($total * $discount / 100);
// Display results
echo "Item Price: $" . $item_price . "<br>";
echo "Quantity: " . $quantity . "<br>";
echo "Discount: " . $discount . "%<br>";
echo "Total Cost after Discount: $" . $total . "<br>";
?>
$result = $a == $b;
Syntax Explanation
● $a and $b :
○ Variables containing values to be compared.
● == :
○ The equal operator returns true if $a is
equal to $b , after type coercion.
● $result :
○ Stores the boolean result of the comparison.
Simple Code Example
<?php
$a = 5;
$b = "5";
$result = $a == $b;
echo "Equal: " . ($result ? "True" : "False"); // Outputs: Equal: True
?>
Notes
● The equal operator performs loose comparison,
converting values to the same type before
comparing.
● It is often used in conditional statements to evaluate
if two values are the same, regardless of type.
Warnings
● Loose comparison can lead to unexpected results if
types are not carefully considered (e.g., "5" == 5 is
true ).
● Use strict comparison ( === ) when type matching
is critical.
<?php
$a = 5;
$b = "5";
$result = $a === $b;
echo "Identical: " . ($result ? "True" : "False"); // Outputs: Identical: False
?>
Notes
● The identical operator is useful for strict
comparison, ensuring both value and type match.
● It is commonly used in data validation and API
responses to ensure precise matches.
Warnings
● The identical operator will return false if the types
do not match, even if the values are the same ( "5"
=== 5 is false ).
● Use the identical operator when handling sensitive
data or validating data types.
Syntax
$result = $a != $b;
Syntax Explanation
● $a and $b :
○ Variables containing values to be compared.
● != or <> :
○ The not equal operator returns true if $a is
not equal to $b , after type coercion.
● $result :
○ Stores the boolean result of the comparison.
Simple Code Example
<?php
$a = 5;
$b = 3;
$result = $a != $b;
echo "Not Equal: " . ($result ? "True" : "False"); // Outputs: Not Equal: True
?>
Notes
● The not equal operator is used for loose
comparison, similar to the equal operator, allowing
type coercion.
● It is commonly used to check if values are different
in conditions and loops.
Warnings
● Be aware of type coercion, as it can lead to
unexpected results ( "5" != 5 is false ).
● Use strict not equal ( !== ) for more precise
comparisons.
Syntax Explanation
● $a and $b :
○ Variables containing values to be compared.
● !== :
○ The not identical operator returns true if $a
and $b are not equal or not of the same type.
● $result :
○ Stores the boolean result of the comparison.
Simple Code Example
<?php
$a = 5;
$b = "5";
$result = $a !== $b;
echo "Not Identical: " . ($result ? "True" : "False"); // Outputs: Not Identical: True
?>
Notes
● The not identical operator is useful for strict
validation, ensuring both values and types are
checked.
● It is often used in secure validation scenarios, like
form inputs or API data handling.
Warnings
● Unlike the not equal operator, the not identical
operator returns true if either the value or the type
does not match.
● Use this operator when handling sensitive data or
validating strict data types.
Notes
● The greater than operator is commonly used in
loops, conditions, and range checks.
● It works with both integers and floats, comparing
numeric values directly.
Warnings
● Ensure that both values are numeric or convertible
to numbers to avoid unexpected results.
● Be aware of float precision when comparing floating-
point numbers.
<?php
$a = 5;
$b = 10;
$result = $a < $b;
echo "Less Than: " . ($result ? "True" : "False"); // Outputs: Less Than: True
?>
Notes
● The less than operator is used for numeric
comparisons, handling lower bounds and limits.
● It is effective in loops and conditions for evaluating
ranges.
Warnings
● Ensure that values are numeric to avoid unexpected
results.
● Use with care when comparing floats, as precision
can affect results.
Syntax Explanation
● $a and $b :
○ Variables containing values to be compared.
● >= :
○ The operator returns true if $a is greater
than or equal to $b .
● $result :
○ Stores the boolean result of the comparison.
Simple Code Example
<?php
$a = 5;
$b = 5;
$result = $a >= $b;
echo "Greater or Equal: " . ($result ? "True" : "False"); // Outputs: Greater or
Equal: True
?>
Notes
● The greater than or equal to operator checks both
conditions in one step, making it useful for inclusive
ranges.
● It works with both integers and floats, evaluating
numeric values directly.
Warnings
● Ensure that both values are numeric to prevent
unexpected behavior.
● Be aware of float precision when using this operator.
Use Purpose
● Compare minimum values, ensuring values do
not fall below a threshold.
● Handle conditions in loops, like setting lower
bounds or limits.
● Evaluate ranges, checking if values are within
acceptable limits.
Syntax
Syntax Explanation
● $a and $b :
○ Variables containing values to be compared.
● <=> :
○ The spaceship operator returns -1 if $a is
less than $b , 0 if they are equal, and 1 if $a
is greater than $b .
● $result :
○ Stores the result of the comparison,
indicating the relationship between $a and
$b .
Simple Code Example
<?php
$a = 5;
$b = 3;
$result = $a <=> $b;
echo "Comparison Result: " . $result; // Outputs: Comparison Result: 1
?>
Notes
● The spaceship operator is useful for sorting
algorithms, as it returns detailed comparison results
in one step.
● It is effective in numeric, string, and combined
comparisons.
Warnings
● Ensure that both values are of comparable types to
avoid unexpected results.
● Use caution when using this operator with floats due
to potential precision issues.
Syntax Explanation
● $a and $b :
○ Variables containing boolean values to be
combined.
● && :
○ The AND operator returns true if both $a
and $b are true.
● $result :
○ Stores the boolean result of the logical
operation.
Simple Code Example
<?php
$is_admin = true;
$is_logged_in = true;
$can_access = $is_admin && $is_logged_in;
echo "Access Granted: " . ($can_access ? "Yes" : "No"); // Outputs: Access
Granted: Yes
?>
Notes
● The AND operator stops evaluating as soon as one
condition is false (short-circuit evaluation).
● It is commonly used in complex conditions where
multiple checks are required.
Warnings
● Ensure that both operands are boolean or can be
converted to boolean to avoid unexpected results.
● Using && has higher precedence than and , so use
parentheses to clarify expressions when needed.
2. OR Operator ( || )
What is the OR Operator
The OR operator ( || ) evaluates to true if at least one of the
conditions is true. It is used when only one of the conditions
needs to be satisfied.
Use Purpose
● Combine conditions where either can be true.
● Handle alternative paths in if statements or
loops.
● Check for multiple possibilities, such as form
fields or user permissions.
Syntax
$result = $a || $b;
Syntax Explanation
● $a and $b :
○ Variables containing boolean values to be
combined.
● || :
○ The OR operator returns true if either $a or
$b is true.
● $result :
○ Stores the boolean result of the logical
operation.
Simple Code Example
<?php
$is_member = false;
$is_guest = true;
$can_view = $is_member || $is_guest;
echo "View Allowed: " . ($can_view ? "Yes" : "No"); // Outputs: View Allowed: Yes
?>
Notes
● The OR operator stops evaluating as soon as one
condition is true (short-circuit evaluation).
● It is useful for handling alternative conditions, such
as user roles or access levels.
Warnings
● Use parentheses to clarify expressions when
combining OR with other operators.
● The || operator has higher precedence than or , so
parentheses may be needed to ensure correct
evaluation.
3. NOT Operator ( ! )
What is the NOT Operator
The NOT operator ( ! ) inverts the boolean value of a
condition, turning true to false and vice versa.
Use Purpose
● Negate conditions, such as checking if a value is
not true.
● Reverse logic, such as denying access or stopping
execution.
● Handle exceptions, like rejecting invalid inputs or
states.
Syntax
$result = !$a;
Syntax Explanation
● $a :
○ A variable containing a boolean value to be
inverted.
● !:
○ The NOT operator inverts the value of $a .
● $result :
○ Stores the negated boolean result of the
logical operation.
Simple Code Example
<?php
$is_logged_in = false;
$must_login = !$is_logged_in;
echo "Must Login: " . ($must_login ? "Yes" : "No"); // Outputs: Must Login: Yes
?>
Notes
● The NOT operator is used to reverse conditions,
often making code more readable by explicitly stating
negative conditions.
● It is frequently used in loops and conditional checks
to handle exceptions or deny access.
Warnings
● Ensure that the operand is boolean or can be
converted to boolean to avoid unexpected results.
● Use the NOT operator carefully, as double negation
( !! ) can make code harder to read.
Syntax Explanation
● $a and $b :
○ Variables containing boolean values to be
combined.
● and :
○ The AND operator returns true if both $a
and $b are true, but it has lower precedence
than && .
● $result :
○ Stores the boolean result of the logical
operation.
<?php
$is_admin = true;
$is_active = false;
$can_manage = $is_admin and $is_active;
echo "Can Manage: " . ($can_manage ? "Yes" : "No"); // Outputs: Can Manage:
No
?>
Notes
● The and operator is useful for simplifying
expressions where operator precedence does not
affect the result.
● It is often used in simpler conditions or where
readability takes priority.
Warnings
● The and operator has lower precedence than && ,
which can cause unexpected results in complex
expressions.
● Use parentheses to clarify expressions when mixing
and with other operators.
5. OR Operator ( or )
What is the OR Operator ( or )
The or operator functions similarly to || , returning true if
either condition is true. It has lower precedence compared
to || .
Use Purpose
● Combine alternative conditions in simpler
expressions.
● Handle cases where either of the conditions can be
true.
● Manage logical flow in straightforward scenarios.
Syntax
$result = $a or $b;
Syntax Explanation
● $a and $b :
○ Variables containing boolean values to be
combined.
● or :
○ The OR operator returns true if either $a or
$b is true, but it has lower precedence than
|| .
● $result :
○ Stores the boolean result of the logical
operation.
Simple Code Example
<?php
$is_admin = false;
$is_editor = true;
$can_edit = $is_admin or $is_editor;
echo "Can Edit: " . ($can_edit ? "Yes" : "No"); // Outputs: Can Edit: Yes
?>
Notes
● The or operator is often used for simpler
conditions or when readability is more important
than operator precedence.
● It provides a clearer alternative for combining
conditions in certain scenarios.
Warnings
● The or operator has lower precedence than || ,
which can affect the outcome of complex
expressions.
● Use parentheses to ensure correct evaluation when
combining or with other operators.
Syntax Explanation
● $a and $b :
○ Variables containing boolean values to be
combined.
● xor :
○ The XOR operator returns true if only one of
the conditions is true.
● $result :
○ Stores the boolean result of the logical
operation.
Simple Code Example
<?php
$is_day = true;
$is_night = false;
$is_light_on = $is_day xor $is_night;
echo "Light On: " . ($is_light_on ? "Yes" : "No"); // Outputs: Light On: Yes
?>
Notes
● The XOR operator is useful for exclusive
conditions, where only one of the conditions must
be true.
● It is effective for toggling states, like user settings or
feature switches.
Warnings
● Ensure that the conditions are truly mutually
exclusive; otherwise, the result may not be as
expected.
Final Project: "Login System Simulation"
Project Goal
● Create a PHP script that uses logical operators to
manage a simple login system.
● Implement checks to determine if a user has valid
credentials and access rights.
Code for This Project
<?php
// User credentials
$username = "admin";
$password = "1234";
// User input
$input_username = "admin";
$input_password = "1234";
// Access conditions
$is_valid_user = ($input_username == $username) && ($input_password ==
$password);
$is_admin = $input_username == "admin";
// Check access
if ($is_valid_user && $is_admin) {
echo "Access Granted: Admin User";
} elseif ($is_valid_user && !$is_admin) {
echo "Access Granted: Regular User";
} else {
echo "Access Denied";
}
?>
Save and Run
● Save the code as login_system.php .
● Run it on a PHP server or use an online PHP
sandbox.
Check Output
The script will display whether access is granted or denied,
based on the user’s credentials and access level.
Summary
This chapter provided a comprehensive overview of PHP
logical operators, covering AND ( && ), OR ( || ), NOT ( ! ),
and their alternatives ( and , or , xor ). It concluded with a
project demonstrating how logical operators can be used for
decision-making and access control in PHP applications.
Chapter-8 PHP Printing Data
Chapter Overview
This chapter covers printing data in PHP, focusing on
different methods for outputting information to the screen.
PHP provides several functions for displaying data, allowing
developers to output text, variables, arrays, and HTML
content.
Chapter Goal
● Understand the different functions for printing data
in PHP.
● Learn how to use various printing methods for text,
variables, arrays, and HTML.
● Explore examples demonstrating the use of different
printing functions.
● Implement a project that utilizes data printing
methods to generate dynamic content.
1. echo
What is echo
The echo statement is one of the most commonly used
functions in PHP for printing data. It outputs one or more
strings, variables, or HTML content to the screen. It is faster
than print and supports concatenation for dynamic output.
Use Purpose
● Display strings and variables directly to the
browser.
● Output HTML content, enabling dynamic web
page generation.
● Combine multiple strings, variables, or HTML
tags into a single output.
Syntax
echo value;
Syntax Explanation
● value :
○ The value to be printed, which can be a
string, variable, or concatenated string.
○ Multiple values can be combined using
commas, but they must be strings or variables.
Simple Code Example
<?php
$name = "Alice";
echo "Hello, " . $name . "!"; // Outputs: Hello, Alice!
?>
Notes
● echo can print multiple arguments separated by
commas, but parentheses are optional and not
required.
● It is the most efficient method for simple output.
Warnings
● echo cannot return a value, so it cannot be used as
part of an expression.
● Be cautious when concatenating variables to avoid
unintended results, especially with uninitialized
variables.
2. print
What is print
The print statement is similar to echo but returns a value
of 1, making it possible to use in expressions. It outputs a
single string or variable to the screen and is slightly slower
than echo .
Use Purpose
● Display strings and variables directly to the
browser.
● Use in expressions due to its return value.
● Output simple content, such as messages or
variables.
Syntax
print value;
Syntax Explanation
● value :
○ The value to be printed, which can be a string
or variable.
○ It does not support printing multiple values or
using commas like echo .
Simple Code Example
<?php
$name = "Bob";
print "Welcome, " . $name . "!"; // Outputs: Welcome, Bob!
?>
Notes
● print returns 1, allowing it to be used in expressions
(e.g., if (print("Hi")) ).
● It is often used interchangeably with echo for
simple output.
Warnings
● Unlike echo , print can only handle one argument,
making it less flexible for concatenation.
● print is slightly slower than echo , so use it when
return value matters.
3. print_r
What is print_r
The print_r function is used to print human-readable
information about arrays, objects, or other complex data
types. It is useful for debugging or displaying array
contents.
Use Purpose
● Display array contents in a readable format.
● Debug arrays, objects, and complex variables
during development.
● Output structured data, such as arrays or objects,
to understand their contents.
Syntax
print_r(array);
Syntax Explanation
●array :
○ The array or object to be printed, displayed in
a structured format.
○ Works with other complex data types as well.
Simple Code Example
<?php
$fruits = array("apple", "banana", "cherry");
print_r($fruits);
/* Outputs:
Array
(
[0] => apple
[1] => banana
[2] => cherry
)
*/
?>
Notes
● print_r outputs array elements in a structured
format, making it useful for debugging.
● It can be used to inspect objects, arrays, and nested
arrays.
Warnings
● print_r is primarily for debugging and should not be
used in production output, as it lacks formatting.
● When used in HTML, it may need <pre> tags for
better readability.
4. var_dump
What is var_dump
The var_dump function outputs detailed information about
variables, including their data type, length, and value. It is
primarily used for debugging complex data structures.
Use Purpose
● Display detailed information about variables,
such as type, value, and size.
● Debug arrays, objects, and complex variables
for development.
● Inspect data types during validation or testing.
Syntax
var_dump(value);
Syntax Explanation
● value :
○ The variable or value to be printed, showing
its type, size, and content.
○ Works with arrays, objects, and other
complex data types.
Simple Code Example
<?php
$num = 10.5;
var_dump($num); // Outputs: float(10.5)
?>
Notes
● var_dump provides more detailed information than
print_r , making it ideal for debugging.
● It displays information about data types, lengths,
and nested structures.
Warnings
● var_dump is meant for debugging and should be
avoided in production, as it can expose sensitive
information.
● When used in web pages, it may need <pre> tags
for better readability.
5. sprintf
What is sprintf
The sprintf function returns a formatted string according to
a specified format. Unlike printf , it does not print directly
but stores the formatted string in a variable.
Use Purpose
● Format strings and variables for more control
over output.
● Store formatted strings in variables for further
processing.
● Create formatted messages, like currency values
or complex outputs.
Syntax
$formatted_string = sprintf(format, values);
Syntax Explanation
● format :
○ The format specifier, defining how the output
should be structured (e.g., %s for string, %d
for integer, %.2f for float with two decimals).
● values :
○ The variables or values to be formatted
according to the specified format.
● $formatted_string :
○ Stores the resulting formatted string for
further use.
Simple Code Example
<?php
$name = "Alice";
$age = 30;
$formatted = sprintf("Name: %s, Age: %d", $name, $age);
echo $formatted; // Outputs: Name: Alice, Age: 30
?>
Notes
● sprintf is useful for creating formatted strings
that can be stored and reused later.
● It provides more control over the formatting of
strings, numbers, and variables.
Warnings
● Ensure that the format specifiers match the
corresponding variable types to avoid errors.
● sprintf does not print the string; use echo to
display it.
6. printf
What is printf
The printf function outputs a formatted string according to
a specified format. It directly prints the formatted result to
the screen, similar to sprintf but with immediate output.
Use Purpose
● Print formatted strings and variables directly to
the screen.
● Control the format of output, such as decimals,
padding, and alignment.
● Generate formatted content, like tables, lists, or
reports.
Syntax
printf(format, values);
Syntax Explanation
● format :
○ The format specifier, defining the structure of
the output (e.g., %s for string, %d for
integer, %.2f for float with two decimals).
● values :
○ The variables or values to be formatted and
printed according to the specified format.
Simple Code Example
<?php
$price = 9.99;
printf("Price: $%.2f", $price); // Outputs: Price: $9.99
?>
Notes
● printf is useful for generating formatted output
in real-time, such as when creating tables or reports.
● It offers greater control over formatting, making it
ideal for structured output.
Warnings
● Ensure that the format specifiers match the
corresponding variable types to avoid incorrect
output.
● printf immediately outputs the formatted string,
unlike sprintf , which returns it.
<?php
// User details
$name = "Alice Johnson";
$age = 28;
$email = "[email protected]";
$interests = array("Reading", "Traveling", "Cooking");
echo "<h3>Interests:</h3>";
print_r($interests);
?>
1. String Concatenation
What is String Concatenation
String concatenation is the process of joining two or more strings
together to form a single string. PHP uses the dot operator ( . ) to
concatenate strings.
Use Purpose
● Combine strings dynamically, such as creating
messages or combining variables with text.
● Build HTML content, such as generating dynamic
elements or attributes.
● Create formatted text, like combining user input with
predefined templates.
Syntax
Syntax Explanation
● $string1 and $string2 :
○ The strings to be concatenated.
● . (Dot operator):
○ Joins two strings together to form a single string.
● $concatenated_string :
○ Stores the resulting concatenated string.
Simple Code Example
<?php
$first_name = "Alice";
$last_name = "Johnson";
$full_name = $first_name . " " . $last_name;
echo "Full Name: " . $full_name; // Outputs: Full Name: Alice Johnson
?>
Notes
● Concatenation is commonly used to combine variables,
strings, and HTML.
● PHP allows concatenating variables of different types,
automatically converting them to strings.
Warnings
● Be careful when concatenating variables with potential
null or undefined values, as this can cause unexpected
results.
● Use clear spacing and delimiters to improve readability
when combining multiple strings.
$length = strlen($string);
Syntax Explanation
● $string :
○ The string whose length is being measured.
● strlen() :
○ A built-in PHP function that returns the number of
characters in the string.
● $length :
○ Stores the length of the string.
Simple Code Example
<?php
$message = "Hello, World!";
$length = strlen($message);
echo "Length: " . $length; // Outputs: Length: 13
?>
Notes
● The strlen function counts spaces and special characters
as part of the string length.
● It is useful for input validation, ensuring that strings meet
length requirements.
Warnings
● Be aware that strlen does not account for multibyte
characters; use mb_strlen for multibyte strings like UTF-8.
● Ensure the variable is a string to avoid unexpected results.
$uppercase_string = strtoupper($string);
Syntax Explanation
● $string :
○ The string to be converted to uppercase.
● strtoupper() :
○ A built-in PHP function that converts the string to
uppercase.
● $uppercase_string :
○ Stores the resulting uppercase string.
Simple Code Example
<?php
$word = "hello";
$uppercase_word = strtoupper($word);
echo $uppercase_word; // Outputs: HELLO
?>
Notes
● strtoupper is useful for formatting text, like making
names, codes, or titles uppercase.
● It is case-insensitive and works with ASCII characters.
Warnings
● Use mb_strtoupper for converting multibyte strings, like
UTF-8 characters, to uppercase.
● It only converts letters; special characters and numbers
remain unchanged.
<?php
$word = "HELLO";
$lowercase_word = strtolower($word);
echo $lowercase_word; // Outputs: hello
?>
Notes
● strtolower is commonly used to prepare text for
consistent, case-insensitive comparisons.
● It is effective for normalizing user input, making data
validation easier.
Warnings
● Use mb_strtolower for converting multibyte strings to
lowercase.
● It only converts letters; special characters and numbers
remain unaffected.
Syntax Explanation
● $number :
○ The floating-point number to be rounded.
● decimals (optional):
○ The number of decimal places to round to. If
omitted, it rounds to the nearest whole number.
● round() :
○ A built-in PHP function that rounds the number.
● $rounded_number :
○ Stores the resulting rounded number.
Simple Code Example
<?php
$price = 4.567;
$rounded_price = round($price, 2);
echo "Rounded Price: " . $rounded_price; // Outputs: Rounded Price: 4.57
?>
Notes
● round is useful for financial calculations, ensuring prices
or amounts are displayed with appropriate precision.
● It supports rounding up or down based on standard
rounding rules.
Warnings
● Be aware of potential precision issues with floating-point
numbers.
● Use ceil or floor for consistent rounding up or down,
respectively.
$absolute_value = abs($number);
Syntax Explanation
● $number :
○
The number whose absolute value is to be
calculated.
● abs() :
○ A built-in PHP function that returns the absolute
value.
● $absolute_value :
○ Stores the resulting absolute value.
Simple Code Example
<?php
$number = -10;
$positive_number = abs($number);
echo "Absolute Value: " . $positive_number; // Outputs: Absolute Value: 10
?>
Notes
● abs is commonly used to calculate distances,
differences, or non-negative results.
● It works with both integers and floats, converting negative
values to positive.
Warnings
● Ensure that the variable is numeric to avoid errors or
unexpected behavior.
● abs only removes the sign; it does not affect the
magnitude of the number.
Syntax Explanation
● $number :
○ The number to be formatted.
● decimals (optional):
○ The number of decimal places to include in the
output.
● number_format() :
○ A built-in PHP function that formats the number.
● $formatted_number :
○ Stores the resulting formatted string.
Simple Code Example
<?php
$amount = 1234.567;
$formatted_amount = number_format($amount, 2);
echo "Formatted Amount: $" . $formatted_amount; // Outputs: Formatted Amount:
$1,234.57
?>
Notes
● number_format is useful for financial displays, ensuring
consistent presentation of prices and amounts.
● It adds commas to thousands and formats decimal places
for better readability.
Warnings
● Ensure that the variable is numeric before formatting.
● Be cautious of potential rounding when specifying decimal
places.
Final Project: "User Report Generator"
Project Goal
● Create a PHP script that generates a formatted user
report, demonstrating string manipulation and numerical
formatting.
● Implement features like string concatenation, string length
checks, and number formatting.
Code for This Project
<?php
// User details
$name = "Alice Johnson";
$age = 28;
$salary = 3500.456;
// String operations
$greeting = "Welcome, " . $name . "!";
$name_length = strlen($name);
// Numerical operations
$formatted_salary = number_format($salary, 2);
$rounded_age = round($age);
// Display results
echo "<h2>User Report</h2>";
echo "Name: " . $name . " (Length: " . $name_length . " characters)<br>";
echo "Age: " . $rounded_age . "<br>";
echo "Monthly Salary: $" . $formatted_salary . "<br>";
?>
1. if Statement
What is the if Statement
The if statement is a basic conditional control structure in
PHP that evaluates whether a condition is true. If the
condition is true, the code block within the if statement is
executed.
Use Purpose
● Execute code conditionally based on a single,
boolean expression.
● Validate user input, like checking if a form field is
filled.
● Control program flow, determining which block of
code should run based on specific conditions.
Syntax
if (condition) {
// Code to execute if condition is true
}
Syntax Explanation
● condition :
○ The expression that evaluates to true or
false . This can be any comparison or logical
expression.
● if :
○ The keyword that initiates the conditional
check.
● Code block:
○ Enclosed in curly braces {} , it runs only if
the condition is true.
Simple Code Example
<?php
$age = 20;
if ($age > 18) {
echo "You are an adult.";
}
// Outputs: You are an adult.
?>
Notes
● The if statement is ideal for basic validation, like
checking if a user is logged in or a field is not empty.
● It helps create clean decision structures by
evaluating a single condition.
Warnings
● Always ensure that the condition is a boolean
expression; non-boolean values may lead to
unexpected behavior.
● If more than one condition needs to be checked,
consider using if-elseif-else or switch for better
clarity.
2. if-else Statement
What is the if-else Statement
The if-else statement extends the if statement by adding
an else block, which executes when the if condition is
false.
Use Purpose
● Provide alternate actions when the primary
condition fails.
● Handle two possible outcomes, like success or
failure in login attempts.
● Ensure fallback code runs when the primary
condition is false.
Syntax
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Syntax Explanation
● else :
○ Specifies a block of code to run if the if
condition is false.
● Code blocks:
○ If the condition is true, the if block executes;
if false, the else block runs.
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are a minor.";
}
// Outputs: You are a minor.
?>
Notes
● Use if-else for binary decision-making, ensuring
either the if block or else block runs.
● It provides clear control flow, especially for
validation checks or error handling.
Warnings
● Avoid complex conditions inside the if block; break
them down into simpler checks if needed.
● Ensure both code blocks are well-structured to avoid
syntax errors.
3. if-elseif-else Statement
What is the if-elseif-else Statement
The if-elseif-else structure extends the basic if-else by
allowing multiple conditions to be checked in sequence. It
executes the block of the first true condition and skips the
rest.
Use Purpose
● Handle multiple conditions sequentially.
● Implement multi-level decision-making, like
grading based on scores.
● Manage complex conditions, where multiple
potential outcomes exist.
Syntax
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Syntax Explanation
● elseif :
○ Adds additional conditions to be checked if
the previous if or elseif was false.
● else :
○ Executes if no preceding conditions are true.
Simple Code Example
<?php
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} elseif ($score >= 60) {
echo "Grade: C";
} else {
echo "Grade: D";
}
// Outputs: Grade: B
?>
Notes
● The if-elseif-else structure is useful for checking
ranges of values.
● It stops evaluating as soon as one condition is true,
improving efficiency.
Warnings
● Use parentheses for complex conditions to clarify
evaluation order.
● Avoid using too many elseif statements, as it may
reduce readability.
4. switch Statement
What is the switch Statement
The switch statement evaluates an expression and
executes the matching case block. It is an efficient
alternative to multiple if-elseif checks when comparing one
variable against many values.
Use Purpose
● Check a variable against multiple possible
values in a cleaner way.
● Simplify complex conditional checks, especially
for menus or commands.
● Group related cases together, reducing
redundancy.
Syntax
switch ($variable) {
case value1:
// Code if $variable equals value1
break;
case value2:
// Code if $variable equals value2
break;
default:
// Code if no cases match
}
Syntax Explanation
● $variable :
○ The variable or expression being evaluated.
● case :
○ Checks if $variable matches the specified
value.
● default :
○ Executes if no case matches.
● break :
○ Stops the execution of subsequent cases,
preventing fall-through.
<?php
$day = "Monday";
switch ($day) {
case "Monday":
echo "Start of the week.";
break;
case "Friday":
echo "Almost weekend!";
break;
default:
echo "Regular day.";
}
// Outputs: Start of the week.
?>
Notes
● The switch statement is ideal for checking
discrete values, like user input or predefined
options.
● Each case must end with break to prevent fall-
through.
Warnings
● Without break , the switch will continue to execute
subsequent cases.
● Ensure that the default case handles unexpected
values to prevent errors.
5. while Loop
What is the while Loop
The while loop repeatedly executes a block of code as long
as the specified condition remains true.
Use Purpose
● Repeat code blocks dynamically, as long as a
condition is true.
● Process dynamic data, like reading files or
handling user input.
● Handle continuous operations, such as checking
user input until it matches criteria.
Syntax
while (condition) {
// Code to execute while condition is true
}
Syntax Explanation
● condition :
○ Evaluates to true or false. The loop continues
while the condition is true.
● while :
○ Starts the loop, evaluating the condition
before each iteration.
Simple Code Example
<?php
$count = 1;
while ($count <= 5) {
echo "Count: $count<br>";
$count++;
}
// Outputs: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
?>
Notes
● The while loop is suitable for indefinite iteration,
running until a condition changes.
● It requires manual counter updates to avoid infinite
loops.
Warnings
● Always ensure that the condition will eventually
become false to prevent infinite loops.
● Properly initialize variables before entering the loop.
6. do-while Loop
What is the do-while Loop
The do-while loop is similar to the while loop but
guarantees at least one execution of the code block, as it
checks the condition after the code runs.
Use Purpose
● Execute code at least once, such as prompting
user input.
● Handle situations where the action precedes
validation, like generating menu options.
● Ensure minimum execution, making it suitable
for repeating prompts or actions.
Syntax
do {
// Code to execute
} while (condition);
Syntax Explanation
● do :
○ Begins the loop, ensuring the code block
executes at least once.
● while :
○ Checks the condition after execution.
Simple Code Example
<?php
$count = 1;
do {
echo "Count: $count<br>";
$count++;
} while ($count <= 5);
// Outputs: Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
?>
Notes
● The do-while loop is useful for prompting and
validating user input, especially when input is
required.
●It differs from the while loop by ensuring the
code runs at least once.
Warnings
● Use with caution, as the condition is checked after
execution, which may lead to unintended outcomes.
● Be aware of variables used in the loop to prevent
undefined behavior.
7. for Loop
What is the for Loop
The for loop executes a block of code a specific number of
times, defined by initialization, condition, and increment.
Use Purpose
● Repeat code blocks a fixed number of times,
such as iterating through arrays.
● Implement index-based iteration, using
initialization, condition, and increment.
● Control iterations explicitly, making it suitable
for loops with known counts.
Syntax
8. foreach Loop
What is the foreach Loop
The foreach loop iterates over arrays or objects, making it
ideal for processing collections.
Use Purpose
● Iterate over array elements, processing each
element individually.
● Handle associative arrays, providing access to
both keys and values.
● Simplify array processing, eliminating manual
index handling.
Syntax
Notes
● The foreach loop is suitable for iterating arrays or
collections.
● It automatically handles indexes and associative
arrays, improving readability.
Warnings
● Ensure the variable is an array or iterable to avoid
errors.
● Modifying the array within the loop may cause
unexpected behavior.
Syntax Table
Seri Array Type Syntax Example
al
No
1 Indexed Array $array = $array =
array(val1, val2); array(1, 2, 3);
2 Associative $array = $array =
Array array(key1 => array("name"
val1, ...); => "Alice");
3 Multidimension $array = $array =
al Array array(array1, array(array(1,2
array2); ), array(3,4));
4 Array Length count($array); count(array(1,
2, 3));
1. Indexed Arrays
What is an Indexed Array
Indexed arrays in PHP store a series of elements, each
identified by a numeric index. The indexes start from 0 by
default, and elements are accessed using these indexes.
Use Purpose
● Store lists of values, like numbers, strings, or
objects.
● Iterate through elements, processing each one
individually.
● Manage ordered collections, like lists, queues, or
sequences.
Syntax
$indexed_array = array(value1, value2, value3);
Syntax Explanation
● value1 , value2 , value3 :
○ Elements of the array, which can be of any
data type.
● array() :
○ A function that creates an array.
Simple Code Example
<?php
$numbers = array(1, 2, 3, 4, 5);
echo $numbers[0]; // Outputs: 1
?>
Notes
● Indexed arrays are useful for storing sequential
data, like a list of numbers or names.
● The array() function can be replaced by shorthand
[] in PHP 5.4 and above.
Warnings
● Ensure that the index exists before accessing it to
avoid errors.
● Be careful of off-by-one errors when iterating through
the array.
2. Associative Arrays
What is an Associative Array
Associative arrays store elements identified by string keys
instead of numeric indexes. Each key-value pair allows for
more descriptive access to data.
Use Purpose
● Store key-value pairs, like names and ages or
product IDs and prices.
● Access elements using keys, making it easy to
retrieve specific data.
● Organize data, providing a more intuitive way to
handle data relationships.
Syntax
Syntax Explanation
● key1 and key2 :
○ String keys used to identify elements in the
array.
● value1 and value2 :
○ The corresponding values associated with
each key.
Simple Code Example
<?php
$person = array("name" => "Alice", "age" => 30);
echo $person["name"]; // Outputs: Alice
?>
Notes
● Associative arrays are ideal for labeling elements,
like representing database records or structured data.
● The keys are case-sensitive and must be unique
within the array.
Warnings
● Accessing a non-existent key will return NULL , which
may lead to unexpected results.
● Ensure that key names are unique to avoid
overwriting values.
3. Multidimensional Arrays
What is a Multidimensional Array
Multidimensional arrays contain arrays as their elements,
allowing for the storage of data in multiple dimensions (e.g.,
rows and columns).
Use Purpose
● Store complex data, like tables or matrices.
● Handle nested data structures, such as JSON-like
data or multidimensional tables.
● Group related data, such as storing a list of users
and their attributes.
Syntax
$multi_array = array(
array(value1, value2),
array(value3, value4)
);
Syntax Explanation
● array() :
○ Contains nested arrays as elements.
● Nested arrays:
○ Each nested array can hold multiple values.
Simple Code Example
<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $matrix[1][2]; // Outputs: 6
?>
Notes
● Multidimensional arrays are useful for representing
grids, tables, or nested records.
● They can have any number of dimensions, depending
on the complexity of the data.
Warnings
● Accessing non-existent indexes or dimensions may
cause errors.
● Use loops, such as foreach , to traverse
multidimensional arrays effectively.
4. Array Length ( count )
What is Array Length ( count )
The count function returns the number of elements in an
array, helping determine the size of the array.
Use Purpose
● Get the size of an array, useful for loops or
conditional checks.
● Validate array contents, ensuring it has elements
before processing.
● Limit loop iterations, based on the number of
array elements.
Syntax
$length = count($array);
Syntax Explanation
● count() :
○ A built-in PHP function that returns the
number of elements in an array.
● $array :
○ The array whose length is being determined.
Simple Code Example
<?php
$fruits = array("apple", "banana", "cherry");
echo count($fruits); // Outputs: 3
?>
Notes
● The count function is essential for controlling
loops that iterate over arrays.
● It works with both indexed and associative arrays.
Warnings
● For multidimensional arrays, count returns the
number of elements in the top-level array.
● Use count($array, COUNT_RECURSIVE) to count all
elements, including nested ones.
Syntax Explanation
● [] :
○ Adds an element to the end of the array.
● new_value :
○ The value to be added to the array.
Simple Code Example
<?php
$colors = array("red", "green");
$colors[] = "blue";
print_r($colors); // Outputs: Array ( [0] => red [1] => green [2] => blue )
?>
Notes
● Adding elements using [] is straightforward and
maintains the array order.
●It can be used with both indexed and associative
arrays, provided a key is not specified.
Warnings
● Appending elements to associative arrays without
specifying a key may lead to numeric indexing.
unset($array[index]);
Syntax Explanation
● $array :
○ The array from which an element is to be
removed.
● index :
○ The index or key of the element to be
removed.
Simple Code Example
<?php
$fruits = array("apple", "banana", "cherry");
unset($fruits[1]);
print_r($fruits); // Outputs: Array ( [0] => apple [2] => cherry )
?>
Notes
● unset can be used to remove elements from both
indexed and associative arrays.
● The array may have gaps in indexing after removal,
which can affect iteration.
Warnings
● Removing elements with unset does not reindex
the array.
● Be cautious when using unset within loops, as it
can cause iteration issues.
Syntax Explanation
● value :
○ The value to search for within the array.
● $array :
○ The array to be searched.
● in_array() :
○ Returns true if the value is found, false
otherwise.
Simple Code Example
<?php
$fruits = array("apple", "banana", "cherry");
if (in_array("banana", $fruits)) {
echo "Banana is in the list.";
}
// Outputs: Banana is in the list.
?>
Notes
● in_array is case-sensitive and returns false if the
case does not match.
● It is commonly used for validation or search
operations.
Warnings
● Be aware of type comparisons; use in_array(value,
$array, true) for strict type checking.
● Avoid searching large arrays frequently, as it may
affect performance.
Final Project: "Inventory Management System"
Project Goal
● Create a PHP script that manages an inventory using
arrays.
● Implement functions to add, remove, update, and
search for items in the inventory.
Code for This Project
<?php
// Initial inventory
$inventory = array("apple" => 50, "banana" => 100, "orange" => 75);
// Add new item
$inventory["grape"] = 60;
// Remove an item
unset($inventory["banana"]);
print_r($inventory);
/*
Outputs:
orange is available with quantity: 75
Array ( [apple] => 70 [orange] => 75 [grape] => 60 )
*/
?>
1. Basic Functions
What is a Basic Function
A function is a block of code that performs a specific task.
Basic functions in PHP are user-defined and allow for code
reuse. They can be called as many times as needed
throughout the program.
Use Purpose
● Organize code into reusable blocks, improving
code clarity.
● Encapsulate logic, making it easier to manage and
maintain.
● Perform repetitive tasks, such as calculations or
data processing.
Syntax
function functionName() {
// Code to execute
}
Syntax Explanation
● function :
○ A keyword that defines a new function.
● functionName :
○ The name of the function, which should be
descriptive of its purpose.
● Code block:
○ Enclosed in curly braces {} , containing the
instructions to be executed when the function
is called.
Simple Code Example
<?php
function greet() {
echo "Hello, World!";
}
greet(); // Outputs: Hello, World!
?>
Notes
● Functions are declared once but can be called
multiple times, making them ideal for code reuse.
● Function names are not case-sensitive in PHP,
meaning greet() and GREET() are considered the
same.
Warnings
● Ensure that functions are defined before calling
them to avoid errors.
● Avoid using reserved keywords as function names to
prevent conflicts.
Notes
● Parameters allow functions to process dynamic
input, making them versatile.
● PHP supports both required and optional
parameters in functions.
Warnings
● Ensure that the correct number of arguments is
passed to functions when calling them.
● Parameter names must be unique within the
function to avoid conflicts.
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(5, 3);
echo $result; // Outputs: 8
?>
Notes
● The return statement exits the function
immediately after execution, returning the specified
value.
● Functions can return any data type, including
strings, numbers, arrays, or objects.
Warnings
● Only one value can be returned from a function, but
it can be an array or object to return multiple values.
● Ensure that the return statement is used correctly;
functions without return will return NULL by default.
Syntax Explanation
● $param = defaultValue :
○ Sets a default value for the parameter, used
if no value is provided.
● Multiple parameters:
○ Default values can be set for one or more
parameters.
Simple Code Example
<?php
function greet($name = "Guest") {
echo "Hello, " . $name . "!";
}
greet(); // Outputs: Hello, Guest!
?>
Notes
● Default parameters make functions more flexible
and easier to use.
● If non-default parameters are present, they must be
listed before parameters with default values.
Warnings
● Ensure that parameters with default values are
listed after required parameters to avoid errors.
● If a parameter with a default value is passed an
argument, the default value is overridden.
Use Purpose
● Control variable visibility, ensuring variables are
used in the intended context.
● Avoid variable conflicts, especially in large
programs.
● Preserve variables between function calls,
using static variables.
Syntax
Local Variables: Defined within a function and accessible
only inside it.
function test() {
$localVar = 10;
}
function counter() {
static $count = 0;
$count++;
echo $count;
}
<?php
$count = 10; // Global variable
function increment() {
global $count;
$count++;
}
increment();
echo $count; // Outputs: 11
?>
Notes
●Local variables exist only within functions, while
global variables exist outside functions.
● Static variables maintain their values between
function calls, making them useful for counters or
accumulators.
Warnings
● Avoid using too many global variables, as they can
lead to conflicts and make debugging harder.
● Static variables should be used carefully to prevent
unintended side effects.
6. Built-in Functions
What are Built-in Functions
PHP has a wide range of built-in functions that perform
common tasks, such as string manipulation, array handling,
mathematical calculations, and file operations.
Use Purpose
● Perform common operations, like counting array
elements or formatting strings.
● Simplify tasks, by using predefined functions for
standard operations.
● Handle data efficiently, using functions optimized
for performance.
Examples of Built-in Functions
● String Functions:
○ strlen() : Returns the length of a string.
○ strtoupper() : Converts a string to uppercase.
● Array Functions:
○ array_push() : Adds elements to an array.
○ array_merge() : Merges two or more arrays.
● Math Functions:
○ abs() : Returns the absolute value of a
number.
○ round() : Rounds a floating-point number.
● File Functions:
○ fopen() : Opens a file.
○ fwrite() : Writes to a file.
Simple Code Example
<?php
$word = "Hello";
echo strlen($word); // Outputs: 5
?>
Notes
● Built-in functions are predefined in PHP and can
be used directly.
● They are optimized for performance and offer a wide
range of functionality.
Warnings
● Be aware of the function’s behavior and potential
side effects, especially with functions that modify
data.
● Some built-in functions may require additional
extensions or settings to be enabled in PHP.
Final Project: "Simple Calculator with
Functions"
Project Goal
● Create a PHP script that acts as a simple calculator
using functions.
● Implement functions to perform addition,
subtraction, multiplication, and division.
Code for This Project
<?php
// Addition function
function add($a, $b) {
return $a + $b;
}
// Subtraction function
function subtract($a, $b) {
return $a - $b;
}
// Multiplication function
function multiply($a, $b) {
return $a * $b;
}
// Division function
function divide($a, $b) {
if ($b != 0) {
return $a / $b;
} else {
return "Error: Division by zero!";
}
}
1. Local Scope
What is Local Scope
Local scope refers to variables defined inside a function.
These variables are only accessible within that function and
cannot be used outside it.
Use Purpose
● Encapsulate data within a function, keeping
variables separate from the global environment.
● Avoid conflicts with global variables, as local
variables are isolated within their functions.
● Improve code readability, by keeping variables
related to specific functions.
Syntax
function functionName() {
$localVar = value;
// $localVar is accessible only within this function
}
Syntax Explanation
● $localVar :
○ A variable declared inside the function,
accessible only within that function.
● Function block:
○ The scope of $localVar is limited to this block.
Simple Code Example
<?php
function showMessage() {
$message = "Hello, World!";
echo $message;
}
showMessage(); // Outputs: Hello, World!
// echo $message; // Error: Undefined variable
?>
Notes
● Variables declared inside a function are local to that
function and cannot be accessed outside it.
● Local variables are reinitialized each time the
function is called, ensuring they do not retain values
between calls.
Warnings
● Attempting to access local variables outside their
function scope will result in an undefined variable
error.
● If variables need to be shared across functions,
consider using global variables or passing parameters.
2. Global Scope
What is Global Scope
Global scope refers to variables defined outside any function,
making them accessible throughout the script. However, to
access global variables inside functions, the global keyword
or $GLOBALS array must be used.
Use Purpose
● Store data globally, making it accessible across
multiple functions.
● Share data between functions without passing
parameters.
● Manage configuration values, like settings or
constants, that need to be accessed globally.
Syntax
$globalVar = value;
function functionName() {
global $globalVar;
// $globalVar can be accessed and modified here
}
Syntax Explanation
● $globalVar :
○ A variable defined in the global scope, outside
of any function.
● global keyword:
○ Allows access to global variables inside
functions.
Simple Code Example
<?php
$count = 10; // Global variable
function increment() {
global $count;
$count++;
}
increment();
echo $count; // Outputs: 11
?>
Notes
● Global variables can be accessed from any part of the
script, provided they are declared global within
functions.
The $GLOBALS array can also be used to access global
variables:
function increment() {
$GLOBALS['count']++;
}
Warnings
● Using too many global variables can make debugging
difficult and may lead to unexpected side effects.
● Avoid variable name conflicts by using descriptive
names for global variables.
3. Static Scope
What is Static Scope
Static scope in PHP refers to variables defined as static
within a function. These variables retain their value between
function calls, unlike regular local variables.
Use Purpose
● Preserve variable state across multiple function
calls.
● Implement counters, accumulators, or caching
mechanisms within functions.
● Store data temporarily, without making variables
global.
Syntax
function functionName() {
static $staticVar = value;
// $staticVar retains its value between calls
}
Syntax Explanation
● static :
○ A keyword that defines a variable as static,
allowing it to retain its value.
● $staticVar :
○ A variable that maintains its value across
function calls.
Simple Code Example
<?php
function counter() {
static $count = 0;
$count++;
echo $count . "<br>";
}
counter(); // Outputs: 1
counter(); // Outputs: 2
counter(); // Outputs: 3
?>
Notes
● Static variables are initialized only once, and their
values persist across subsequent calls to the function.
● They are useful for maintaining state within a
function, such as keeping track of the number of times
a function has been called.
Warnings
● Static variables are local to the function and
cannot be accessed globally.
● Be cautious when using static variables in recursive
functions, as they may not behave as expected.
4. Parameter Scope
What is Parameter Scope
Function parameters act as local variables within the
function, holding values passed to the function when it is
called. They allow functions to receive input and process data
accordingly.
Use Purpose
● Pass data into functions, making them versatile
and reusable.
● Control function behavior, based on the values of
parameters.
● Handle dynamic input, allowing functions to work
with different data each time they are called.
Syntax
Syntax Explanation
● $param1 , $param2 :
○ Parameters that hold values passed to the
function.
● Function block:
○ Parameters are treated as local variables
within this block.
Simple Code Example
<?php
function add($a, $b) {
return $a + $b;
}
Notes
● Parameters provide a way to pass values into
functions, making them adaptable to various inputs.
● Parameters are treated as local variables, meaning
they are accessible only within the function.
Warnings
● Ensure that the number of arguments matches the
number of parameters when calling functions to avoid
errors.
● Modifying parameter values inside the function does
not affect the original variables passed, as they are
passed by value by default.
Syntax Table
Seri Superglob Purpose Example
al al
No
1 $_GET Access data sent $_GET['name']
via URL (GET
method)
1. $_GET
What is $_GET
The $_GET superglobal is an associative array that contains
data sent to the script via the URL (query string) or forms
that use the GET method. It is primarily used to pass data
between pages using URL parameters.
Use Purpose
● Retrieve data from URLs, allowing users to send
variables and values in the URL.
● Collect form data, especially for search forms or
filters, where data is not sensitive.
● Pass variables between pages, like session IDs,
pagination numbers, or user selections.
Syntax
$value = $_GET['key'];
Syntax Explanation
● $_GET :
○ A built-in associative array that stores data
sent via the URL.
● 'key' :
○ The name of the parameter in the URL or GET
form.
Simple Code Example
<?php
// URL: http://example.com/index.php?name=Alice
if (isset($_GET['name'])) {
$name = $_GET['name'];
echo "Hello, " . htmlspecialchars($name) . "!";
}
// Outputs: Hello, Alice!
?>
Notes
● Use htmlspecialchars() to prevent XSS attacks when
outputting user-supplied data.
● The maximum length of a URL (including GET
parameters) is browser-dependent, but generally
around 2,048 characters.
Warnings
● Data sent via GET is visible in the URL, making it
unsuitable for sensitive data like passwords.
● Always validate and sanitize user input to avoid
security vulnerabilities.
2. $_POST
What is $_POST
The $_POST superglobal is an associative array that collects
data sent to the script using the POST method, typically from
HTML forms. It is widely used for forms that modify data,
such as login, registration, or file uploads.
Use Purpose
● Handle form submissions, especially when dealing
with sensitive information, like login credentials or
user registration.
● Pass large amounts of data, as POST does not
have size limitations like GET.
● Process user input, such as adding, updating, or
deleting records in a database.
Syntax
$value = $_POST['key'];
Syntax Explanation
● $_POST :
○ An associative array that contains data sent
using the POST method.
● 'key' :
○ The name of the form field to retrieve data
from.
Simple Code Example
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['username'])) {
$username = $_POST['username'];
echo "Welcome, " . htmlspecialchars($username) . "!";
}
?>
Notes
● POST data is sent in the request body, making it
more secure than GET for handling sensitive
information.
● Use isset() to check if a form field exists before
accessing it to avoid errors.
Warnings
● Always validate and sanitize POST data to prevent
security risks like SQL injection.
● Ensure forms use the POST method to keep data
secure and hidden from the URL.
3. $_REQUEST
What is $_REQUEST
The $_REQUEST superglobal is a combined associative array
of GET, POST, and COOKIE data. It provides a general way to
access data, regardless of how it was sent to the server.
Use Purpose
● Access form data dynamically, without
considering the request method.
● Handle variables from multiple sources (GET,
POST, COOKIE).
● Simplify quick prototyping, where the source of
data is not a concern.
Syntax
$value = $_REQUEST['key'];
Syntax Explanation
● $_REQUEST :
○ An associative array that combines data from
GET, POST, and COOKIE.
● 'key' :
○ The name of the variable to be accessed from
any source.
Simple Code Example
<?php
if (isset($_REQUEST['name'])) {
$name = $_REQUEST['name'];
echo "Hello, " . htmlspecialchars($name) . "!";
}
?>
Notes
● $_REQUEST is convenient for basic input handling,
but it is less secure since it merges data from different
sources.
● Use it cautiously, as it may introduce unintentional
behavior if the same key exists in GET, POST, or
COOKIE.
Warnings
● Avoid using $_REQUEST for critical operations, as it
can be less predictable than specifying the exact
superglobal.
● Always sanitize data, as mixing sources may
introduce security risks.
4. $_SESSION
What is $_SESSION
The $_SESSION superglobal is an associative array used to
store and retrieve data across multiple pages in a web
application. Session variables are stored on the server and
persist until the session ends or is manually destroyed.
Use Purpose
● Maintain user sessions, like login state or cart
items, across multiple pages.
● Store user-specific data, such as preferences,
settings, or permissions.
● Track user interactions, enabling personalization
and continuity.
Syntax
$_SESSION['key'] = value;
Syntax Explanation
● $_SESSION :
○ An associative array that stores session data.
● 'key' :
○ The name of the session variable to be set or
accessed.
Simple Code Example
<?php
session_start(); // Start the session
$_SESSION['user'] = "Alice";
echo "User: " . $_SESSION['user']; // Outputs: User: Alice
?>
Notes
● Always start the session using session_start() before
accessing session variables.
● Session variables are stored server-side, making
them secure for sensitive data.
Warnings
● Session data can consume server resources, so clear
unnecessary session variables when no longer needed.
● Protect session IDs from exposure by using secure
transmission (HTTPS).
5. $_COOKIE
What is $_COOKIE
The $_COOKIE superglobal is an associative array that
retrieves data stored in cookies on the client-side. Cookies
are small pieces of data stored on the user's browser to
maintain information across sessions.
Use Purpose
● Store user preferences, like theme selection or
language choice, for later use.
● Remember user login information, such as
session tokens for automatic logins.
● Track user behavior, useful for analytics and
personalization.
Syntax
$value = $_COOKIE['key'];
Syntax Explanation
● $_COOKIE :
○ An associative array that stores cookie data.
● 'key' :
○ The name of the cookie to retrieve.
Simple Code Example
<?php
setcookie("user", "Alice", time() + (86400 * 30)); // Set a cookie for 30 days
if (isset($_COOKIE['user'])) {
echo "Welcome back, " . $_COOKIE['user'] . "!";
}
// Outputs: Welcome back, Alice!
?>
Notes
● Cookies are stored on the client-side, making
them visible and editable by the user.
● Use setcookie() to set cookies and define expiry
times.
Warnings
● Limit cookie size to 4KB, as most browsers have this
restriction.
● Use secure cookie settings, like HttpOnly and
Secure , to prevent JavaScript access and insecure
transmission.
6. $_SERVER
What is $_SERVER
The $_SERVER superglobal is an associative array that
contains information about the server environment and the
current request. It provides details like headers, script paths,
and server settings.
Use Purpose
● Retrieve server and script information, such as
file paths or server names.
● Access request details, like the request method,
client IP address, or HTTP headers.
● Debug server and request environment, helpful
for understanding the server context.
Syntax
$value = $_SERVER['key'];
Syntax Explanation
● $_SERVER :
○ An associative array that contains server and
request data.
● 'key' :
○ The specific server information to retrieve.
Simple Code Example
<?php
echo "Current Script: " . $_SERVER['PHP_SELF']; // Outputs the script's filename
?>
Notes
● Common keys include:
○ 'PHP_SELF' : The current script's path.
○ 'SERVER_NAME' : The server's hostname.
○ 'REQUEST_METHOD' : The request method
(GET, POST, etc.).
Warnings
● Be cautious when using user-manipulated values
from $_SERVER , as they can be used in attacks (e.g.,
HTTP_USER_AGENT or REFERER ).
● Always sanitize output before displaying it to prevent
XSS vulnerabilities.
Final Project: "User Login System with
Superglobals"
Project Goal
● Create a PHP script that handles user login using
$_POST for form submission and manages user
sessions using $_SESSION .
● Demonstrate setting and retrieving cookies for user
preferences.
Code for This Project
<?php
session_start(); // Start session
<?php
$file = fopen("example.txt", "r");
if ($file) {
echo "File opened successfully.";
fclose($file);
}
?>
Notes
● Always check if fopen() is successful before proceeding
with file operations.
● Use appropriate file modes to prevent unintentional data
loss (e.g., using "w" will erase existing content).
Warnings
● Be cautious with "w" mode, as it erases the existing
content of the file.
● Ensure proper permissions are set on the file or directory to
avoid access errors.
2. Reading Files ( fread and file_get_contents )
What is Reading Files
Reading files in PHP can be done using fread() for reading a
specified number of bytes, or file_get_contents() for reading the
entire file into a string.
Use Purpose
● Extract file contents, such as configuration settings, logs,
or data files.
● Process large files in chunks using fread() .
● Retrieve entire file contents for quick access using
file_get_contents() .
Syntax
Syntax Explanation
● $file :
○ The file resource obtained from fopen() .
● $length :
○ The number of bytes to read from the file.
Simple Code Example
<?php
$file = fopen("example.txt", "r");
if ($file) {
$content = fread($file, filesize("example.txt"));
echo $content;
fclose($file);
}
?>
Notes
● Use filesize() to read the entire file when using fread() .
● file_get_contents() is more straightforward for reading the
full content of a file.
Warnings
● Ensure the file is not too large when using
file_get_contents() , as it may exhaust memory.
● Always check if the file exists before reading to avoid errors.
3. Writing to Files ( fwrite and file_put_contents )
What is Writing to Files
Writing to files in PHP can be done using fwrite() to write data to an
open file resource or file_put_contents() to write data directly to a
file.
Use Purpose
● Store new data in files, such as logs, user data, or reports.
● Create new files or overwrite existing files with new
content.
● Append data to files without altering existing content.
Syntax
fwrite($file, $string);
Syntax Explanation
● $file :
○ The file resource obtained from fopen() .
● $string :
○ The string to be written to the file.
Simple Code Example
<?php
$file = fopen("example.txt", "w");
if ($file) {
fwrite($file, "Hello, PHP File Handling!");
fclose($file);
}
?>
Notes
● Use "a" mode to append data without overwriting existing
content.
● file_put_contents() is an alternative for writing strings
directly to a file.
Warnings
● Be cautious when using "w" mode, as it overwrites existing
content.
● Ensure proper permissions for writing to files, especially in
web environments.
fclose($file);
Syntax Explanation
● $file :
○ The file resource to be closed, obtained from
fopen() .
Simple Code Example
<?php
$file = fopen("example.txt", "r");
if ($file) {
// Perform file operations
fclose($file);
}
?>
Notes
●Always close files after completing file operations to free up
resources.
● Closing files ensures that data is written to the file and the
file is no longer locked.
Warnings
● Attempting to use a closed file resource will result in errors.
● Forgetting to close files can lead to memory leaks and data
corruption.
$fileExists = file_exists($filename);
Syntax Explanation
● $filename :
○ The name of the file to check for existence.
Simple Code Example
<?php
if (file_exists("example.txt")) {
echo "File exists.";
} else {
echo "File does not exist.";
}
?>
Notes
● Use file_exists() for basic file validation before
performing file operations.
● It works with both files and directories.
Warnings
● On large directories, file_exists() can be slow; use it
judiciously.
● Ensure the correct file path is provided to avoid false
negatives.
unlink($filename);
Syntax Explanation
● $filename :
○ The name of the file to be deleted.
Simple Code Example
<?php
if (file_exists("example.txt")) {
unlink("example.txt");
echo "File deleted.";
} else {
echo "File not found.";
}
?>
Notes
● Always check if a file exists before attempting to delete it.
● Use unlink() with caution, as deleted files cannot be
recovered.
Warnings
● Ensure correct permissions before attempting to delete a
file.
● Avoid using unlink() on sensitive files without proper
validation.
Final Project: "Simple File-Based Notepad"
Project Goal
● Create a PHP script that reads, writes, appends, and deletes
text files.
● Implement basic file handling functions to manage a simple
file-based notepad.
Code for This Project
<?php
// Create or write to a file
if (isset($_POST['save'])) {
$filename = "notes.txt";
$content = $_POST['content'];
file_put_contents($filename, $content);
echo "File saved successfully!";
}
session_start();
$_SESSION['key'] = value;
Syntax Explanation
● session_start() :
○ Initializes the session, making the
$_SESSION superglobal available.
● $_SESSION['key'] :
○ Stores a value in the session with the
specified key.
Simple Code Example
<?php
session_start(); // Start the session
Notes
● The session_start() function must be called at the
beginning of the script, before any HTML output.
● Session data is stored server-side, making it more
secure for sensitive information like passwords or
user IDs.
Warnings
● Always use secure measures (like HTTPS) to prevent
session hijacking.
● Clear session variables using session_unset() and
end sessions with session_destroy() when no longer
needed.
$_SESSION['key'] = value;
Syntax Explanation
● $_SESSION['key'] :
○ Sets a session variable with the given key to
the specified value.
Simple Code Example
<?php
session_start(); // Start the session
$_SESSION['user_id'] = 12345;
echo "User ID is " . $_SESSION['user_id']; // Outputs: User ID is 12345
?>
Notes
● Session variables persist until the session ends or is
manually cleared.
● They are commonly used for user authentication,
preferences, and temporary storage.
Warnings
● Session variables should not store large amounts of
data, as it can impact server performance.
● Make sure to validate and sanitize any data stored in
sessions to prevent security vulnerabilities.
Syntax
$value = $_SESSION['key'];
Syntax Explanation
● $_SESSION['key'] :
○ Retrieves the value of the specified session
variable.
Simple Code Example
<?php
session_start(); // Start the session
if (isset($_SESSION['username'])) {
echo "Welcome back, " . $_SESSION['username'] . "!";
} else {
echo "Please log in.";
}
?>
Notes
● Always check if a session variable is set using
isset() before accessing it to avoid errors.
● Session variables are server-side, so they are not
visible to users, making them suitable for sensitive
data.
Warnings
● Session variables may persist longer than expected;
use session_unset() to clear variables when they are
no longer needed.
● Avoid storing passwords or highly sensitive
information in session variables.
4. Destroying Sessions
What is Destroying Sessions
Destroying a session removes all stored data and ends the
session. It is useful when logging users out or clearing all
session variables.
Use Purpose
● Log users out, clearing all session data to ensure
security.
● End the session completely, preventing further
access to session variables.
● Reset session data, clearing any temporary
information stored during the session.
Syntax
session_unset();
session_destroy();
Syntax Explanation
● session_unset() :
○ Clears all session variables but keeps the
session active.
● session_destroy() :
○ Ends the session and clears all session data.
Simple Code Example
<?php
session_start(); // Start the session
// Log out and destroy session
session_unset();
session_destroy();
echo "You have been logged out.";
?>
Notes
● Use both session_unset() and session_destroy() to
ensure all session data is cleared.
● After destroying a session, you must call
session_start() to create a new session if needed.
Warnings
● After destroying a session, session variables are no
longer accessible.
● Ensure that users are properly redirected after
logging out to avoid confusion.
5. Cookies
What are Cookies
Cookies are small files stored on the user's browser that
contain key-value pairs. They are used to maintain data
across sessions, remember user preferences, and track user
behavior.
Use Purpose
● Store user preferences, like language or theme,
to provide a personalized experience.
● Remember user login information, enabling
automatic logins.
● Track user behavior, useful for analytics and
marketing.
Syntax
Syntax Explanation
● 'name' :
○ The name of the cookie to be set.
● 'value' :
○ The value to be stored in the cookie.
● $expire :
○ The expiration time of the cookie, specified as
a Unix timestamp.
Simple Code Example
<?php
setcookie("user", "Alice", time() + 3600); // Set a cookie for 1 hour
if (isset($_COOKIE['user'])) {
echo "Welcome back, " . $_COOKIE['user'] . "!";
}
// Outputs: Welcome back, Alice!
?>
Notes
● Cookies are stored client-side and sent with each
HTTP request, making them suitable for non-sensitive
data.
● Use setcookie() before any HTML output, as cookies
are set in the HTTP headers.
Warnings
● Cookies can be modified by users, so they should
not be used for sensitive information.
● Use secure cookie settings, like HttpOnly and
Secure , to protect cookies from JavaScript access and
insecure transmission.
6. Retrieving Cookies
What is Retrieving Cookies
Cookies can be accessed using the $_COOKIE superglobal,
which contains all the cookies set by the server and sent by
the client.
Use Purpose
● Access stored user preferences, like theme or
language settings.
● Retrieve persistent data, such as last login or
selected filters.
● Display personalized content, based on stored
cookies.
Syntax
$value = $_COOKIE['name'];
Syntax Explanation
● $_COOKIE['name'] :
○ Retrieves the value of the specified cookie.
Simple Code Example
<?php
if (isset($_COOKIE['user'])) {
echo "User: " . $_COOKIE['user'];
} else {
echo "No user found.";
}
?>
Notes
● Use isset() to check if a cookie exists before
accessing it to avoid errors.
● Cookies are useful for storing non-sensitive data
across multiple sessions.
Warnings
● Always validate and sanitize cookie values to
prevent security risks like XSS.
● Cookies can be deleted or modified by users, so do
not rely solely on cookies for authentication.
7. Deleting Cookies
What is Deleting Cookies
Cookies can be deleted by setting their expiration time to a
past date, effectively removing them from the client’s
browser.
Use Purpose
● Clear stored user data, like preferences or login
tokens, when logging out.
● Reset cookies, removing outdated or unused data.
● Ensure privacy, by deleting cookies that are no
longer needed.
Syntax
Syntax Explanation
● 'name' :
○ The name of the cookie to be deleted.
● '' :
○ Sets the cookie’s value to an empty string.
● time() - 3600 :
○ Sets the expiration time to one hour in the
past, deleting the cookie.
Simple Code Example
<?php
setcookie("user", "", time() - 3600); // Delete the cookie
echo "User cookie has been deleted.";
?>
Notes
● Deleting a cookie requires setting the same path
and domain as when it was created.
● Use cookie deletion for logouts, clearing
preferences, or resetting user data.
Warnings
● Deleting a cookie does not guarantee its immediate
removal; the browser may retain it until the next
request.
● Ensure that cookie settings (path, domain) match
when deleting to avoid issues.
<?php
session_start(); // Start session
Chapter-18 Object-Oriented
Programming (OOP) in PHP
Chapter Overview
This chapter covers the fundamentals of Object-Oriented
Programming (OOP) in PHP. OOP is a programming paradigm
based on the concept of objects, which are instances of
classes that encapsulate data and behaviors. OOP makes
PHP code more modular, reusable, and maintainable,
making it an essential technique for building complex web
applications.
Chapter Goal
● Understand the basic concepts of OOP, such as
classes, objects, properties, and methods.
● Learn how to create and use classes and objects in
PHP.
● Explore OOP principles like inheritance,
encapsulation, and polymorphism.
● Implement a simple project that demonstrates OOP
concepts in PHP.
class ClassName {
// Properties
public $property;
// Methods
public function methodName() {
// Code
}
}
// Creating an object
$obj = new ClassName();
Syntax Explanation
● class ClassName :
○ Declares a new class named ClassName .
● $property :
○ A variable declared within the class to store
data (property).
● methodName() :
○ A function declared within the class to define
behavior (method).
● new ClassName() :
○ Creates a new object of the class.
Simple Code Example
<?php
class Car {
public $color;
class ClassName {
public $property; // Property
Syntax Explanation
● $property :
○ Stores data related to the object, such as
name, age, or color.
● methodName() :
○ Performs actions related to the object, like
calculating values or interacting with other
methods.
Simple Code Example
<?php
class Car {
public $color;
Notes
● Use $this->property to access properties inside
methods within the class.
● Properties and methods are encapsulated within
the class, keeping data and behavior together.
Warnings
● Always initialize properties before using them to
avoid undefined errors.
● Be cautious with property visibility ( public , private ,
protected ), as it affects access.
3. Constructors
What are Constructors
Constructors are special methods automatically called when
an object is instantiated. They are used to initialize object
properties and set up initial conditions for the object.
Use Purpose
● Initialize object properties, like setting default
values or requiring specific parameters.
● Prepare objects for use, such as establishing
connections or loading initial data.
● Ensure objects have required data, preventing
incomplete or invalid states.
Syntax
class ClassName {
public function __construct($param) {
$this->property = $param;
}
}
Syntax Explanation
● __construct() :
○ A special method called when an object is
created.
● $param :
○ A parameter passed during object creation,
used to initialize properties.
<?php
class Car {
public $color;
Notes
● Constructors provide a way to initialize objects
with specific properties.
● They help ensure objects are ready to use
immediately after creation.
Warnings
● If a class has a constructor, passing the correct
number of arguments during instantiation is
mandatory.
● Avoid complex logic inside constructors, as it may
complicate object creation.
4. Inheritance
What is Inheritance
Inheritance allows one class (child) to inherit properties and
methods from another class (parent). It promotes code
reuse and hierarchical class structures.
Use Purpose
● Reuse existing code, allowing child classes to
inherit functionality from parent classes.
● Extend or override parent behavior, adding or
modifying methods and properties.
● Create hierarchical relationships, modeling real-
world entities with shared characteristics.
Syntax
Syntax Explanation
● extends ParentClass :
○ Specifies that the child class inherits from the
parent class.
● ChildClass:
○ The new class that inherits properties and
methods from the parent class.
Simple Code Example
<?php
class Car {
public function start() {
return "Car started.";
}
}
Notes
● Inheritance enables code reuse, making child
classes inherit parent class features.
● Use parent::method() to call a parent method from
a child class.
Warnings
● Be careful with method names to avoid
unintentional overriding in child classes.
● Deep inheritance hierarchies can make debugging
more difficult.
5. Encapsulation
What is Encapsulation
Encapsulation is the concept of bundling data (properties)
and methods that operate on the data within a single unit
(class). It restricts access to certain components, making
the data secure.
Use Purpose
●
Hide internal details, exposing only necessary
information to users.
● Control access to properties, allowing methods
to manage data changes.
● Improve code maintainability, ensuring that
internal implementation can change without affecting
external code.
Syntax
class ClassName {
private $property;
Syntax Explanation
● private $property :
○ Restricts access to the property within the
class.
● setProperty() and getProperty() :
○ Methods used to access and modify private
properties.
Simple Code Example
<?php
class Car {
private $speed;
Notes
● Encapsulation improves data security by
controlling property access.
● Use getters and setters to manage property access
and modification.
Warnings
● Avoid direct access to private properties from
outside the class.
● Make use of access modifiers ( private , protected ,
public ) appropriately to enforce encapsulation.
6. Polymorphism
What is Polymorphism
Polymorphism allows methods to perform different actions
based on the object that calls them. It enables method
overriding, where a subclass can redefine a method
inherited from the parent class.
Use Purpose
● Implement flexible code, where methods behave
differently based on the calling object.
● Override parent methods, adapting them to
specific needs of child classes.
● Create a consistent interface, while allowing
varied behavior across classes.
Syntax
class ParentClass {
public function methodName() {
// Code
}
}
Syntax Explanation
● Method overriding:
○ Occurs when a child class redefines a method
from its parent class.
● methodName() :
○ The method that exhibits polymorphic
behavior.
Simple Code Example
<?php
class Car {
public function start() {
return "Car started.";
}
}
Notes
● Polymorphism enables dynamic behavior, making
classes more adaptable to changing requirements.
● Use parent::methodName() in the child class to call
the parent’s method.
Warnings
● Be aware of method names in parent and child
classes to avoid unintended behavior.
● Ensure consistent interfaces in polymorphic
methods to maintain compatibility.
<?php
// Parent class
class Vehicle {
protected $brand;
protected $speed;
// Child class
class Car extends Vehicle {
private $type;
Warnings: Indicate issues that may not stop script execution but need
attention.
Fatal Errors: Stop script execution and must be fixed for the script to run.
Notes
● Notices are often related to uninitialized variables or array
indexes.
● Warnings usually occur when the script tries to perform actions
that may not be critical but need attention.
● Fatal Errors stop script execution, making them the most severe
type of error.
Warnings
● Use error reporting to identify and fix notices and warnings
during development.
● Handle fatal errors promptly to prevent script termination.
<?php
// Report all errors
error_reporting(E_ALL);
Notes
● Use E_ALL to report all errors during development for effective
debugging.
● Set error reporting to 0 in production to hide error messages from
users.
Warnings
● Avoid displaying detailed error messages in production, as they
may expose sensitive information.
● Use error logging in production to keep track of issues without
revealing them to users.
Syntax
set_error_handler("customErrorHandler");
Syntax Explanation
● set_error_handler() :
○ Sets a custom error handler function for the script.
● customErrorHandler :
○ The function name that will handle errors.
Simple Code Example
<?php
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr in $errfile on line $errline";
}
set_error_handler("myErrorHandler");
// Trigger an error
echo $undefinedVar;
?>
Notes
● Custom error handlers provide more control over how errors are
managed and displayed.
● Use error logging inside custom handlers to keep track of errors.
Warnings
● Make sure the custom error handler is defined before setting it with
set_error_handler() .
● Avoid using custom error handling for fatal errors, as they may not
be caught.
4. Triggering User Errors ( trigger_error )
What is Triggering User Errors
The trigger_error() function allows developers to trigger user-defined errors
in code. It helps in managing errors manually, especially for validation or
custom logic failures.
Use Purpose
● Generate custom errors, such as validation failures or
unexpected conditions.
● Handle errors explicitly, providing custom error messages.
● Test error handling mechanisms, ensuring they work as
expected.
Syntax
trigger_error(message, type);
Syntax Explanation
● message :
○ The custom error message to display.
● type :
○ The type of user error to trigger, such as
E_USER_WARNING or E_USER_ERROR .
Simple Code Example
<?php
function divide($num, $den) {
if ($den == 0) {
trigger_error("Cannot divide by zero", E_USER_ERROR);
}
return $num / $den;
}
Notes
● Use E_USER_NOTICE , E_USER_WARNING , and E_USER_ERROR for
different levels of user errors.
● Custom error messages help users understand the problem more
clearly.
Warnings
● Be careful when triggering E_USER_ERROR , as it stops script
execution.
● Validate input to prevent unnecessary user errors.
<?php
try {
throw new Exception("This is an exception!");
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Notes
● Use throw to generate exceptions manually.
● Exception handling makes error management more structured and
reliable.
Warnings
● Not all errors are exceptions; use exceptions for cases that require
structured error handling.
● Catch specific exceptions to prevent catching unintended errors.
<?php
$data = array("name" => "Alice", "age" => 30);
// Using var_dump
var_dump($data);
// Using print_r
print_r($data);
// Using error_log
error_log("An error occurred!");
?>
Notes
● Use var_dump() for detailed debugging during development.
● Use error_log() in production to log errors without exposing them
to users.
Warnings
● Avoid using var_dump() or print_r() in production, as they may
expose sensitive information.
● Check error log files regularly to monitor errors in production.
<?php
// Custom error handler
function myErrorHandler($errno, $errstr, $errfile, $errline) {
echo "Error [$errno]: $errstr in $errfile on line $errline";
}
set_error_handler("myErrorHandler");
// Calculator function
function divide($num, $den) {
if ($den == 0) {
trigger_error("Cannot divide by zero", E_USER_WARNING);
return false;
}
return $num / $den;
}
try {
// Perform division
$result = divide(10, 0);
if ($result !== false) {
echo "Result: $result";
}
} catch (Exception $e) {
echo "Caught exception: " . $e->getMessage();
}
?>
Save and Run
● Save the code as calculator.php .
● Run it on a PHP server or use an online PHP sandbox.
Check Output
The script will attempt to divide numbers and handle division by zero using
custom error handling and exception handling.
Summary
This chapter provided a comprehensive look at error handling and
debugging in PHP, covering error types, error reporting, custom error
handling, exceptions, and debugging tools. It concluded with a simple
calculator project that demonstrates error handling and debugging
techniques in practice.
Notes
● Use mysqli or PDO for database interaction;
mysqli is easier for beginners, while PDO offers
more features.
● Always check for connection errors using $conn-
>connect_error to prevent issues.
Warnings
● Never hard-code sensitive information (e.g.,
passwords) directly in the script; use environment
variables for better security.
● Close the connection using $conn->close() to free
resources.
<?php
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . "<br>";
}
} else {
echo "No results found.";
}
?>
Notes
● Use fetch_assoc() to fetch results as an associative
array.
● Use num_rows to check if the query returns any
rows.
Warnings
● Ensure that SQL queries are properly formatted to
prevent syntax errors.
● Check if the query is successful using if ($result)
before processing results.
3. Prepared Statements
What are Prepared Statements
Prepared statements are used to execute SQL queries
securely by separating SQL syntax from data inputs,
preventing SQL injection attacks. They involve preparing the
SQL statement, binding parameters, and executing it.
Use Purpose
● Prevent SQL injection attacks, making database
interaction more secure.
● Improve performance for repeated execution of
similar queries.
● Handle dynamic data, such as user input, safely.
Syntax
$stmt = $conn->prepare($sql);
$stmt->bind_param($types, $variables);
$stmt->execute();
Syntax Explanation
● $stmt->prepare() :
○ Prepares an SQL statement for execution.
● bind_param() :
○ Binds variables to placeholders in the SQL
statement.
● $types :
○ Specifies data types for variables (e.g., "s"
for string, "i" for integer).
Simple Code Example
<?php
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = "Alice";
$email = "[email protected]";
$stmt->execute();
4. Fetching Results
What is Fetching Results
Fetching results refers to retrieving data from the result of a
SELECT query and processing it within the PHP script.
Use Purpose
● Retrieve and display data, such as user details or
product listings.
● Process result sets, handling rows returned from
queries.
● Iterate through results, using loops to manage
fetched data.
Syntax
Syntax Explanation
● fetch_assoc() :
○ Fetches a result row as an associative array.
● $row :
○ Represents the current row being fetched
from the result set.
Simple Code Example
<?php
$sql = "SELECT name, email FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "Name: " . $row["name"] . ", Email: " . $row["email"] . "<br>";
}
} else {
echo "No results found.";
}
?>
Notes
● Use fetch_assoc() to retrieve results as an
associative array, making data processing more
intuitive.
● Check num_rows before fetching to ensure the
query returned results.
Warnings
● Ensure that fetched results are properly sanitized
before displaying them to avoid XSS attacks.
● Handle cases where the result set is empty to
prevent unexpected behavior.
5. Updating Records
What is Updating Records
Updating records involves modifying existing data in the
database using the SQL UPDATE statement.
Use Purpose
● Change existing data, such as updating user
details or order status.
● Modify multiple records, using conditions like
WHERE clauses.
● Adjust records dynamically, based on user
actions or input.
Syntax
$sql = "UPDATE table_name SET column_name = ? WHERE condition";
$stmt = $conn->prepare($sql);
$stmt->bind_param("type", $value);
$stmt->execute();
Syntax Explanation
● UPDATE table_name :
○ Modifies data in the specified table.
● SET column_name = ? :
○ Sets the new value for the specified column.
● WHERE condition :
○ Restricts the update to matching records.
<?php
$stmt = $conn->prepare("UPDATE users SET email = ? WHERE name = ?");
$stmt->bind_param("ss", $email, $name);
$email = "[email protected]";
$name = "Alice";
$stmt->execute();
Notes
● Always use WHERE clauses to prevent accidental
updates to all records.
● Use prepared statements to prevent SQL injection
when updating records.
Warnings
● Avoid updating records without a WHERE clause to
prevent unintended modifications.
● Check if the update was successful using $stmt-
>affected_rows .
6. Deleting Records
What is Deleting Records
Deleting records involves removing data from a table using
the SQL DELETE statement.
Use Purpose
● Remove obsolete data, like outdated records or
canceled orders.
● Manage database size, by clearing unneeded
entries.
● Handle user actions, like account deletion or item
removal.
Syntax
Syntax Explanation
● DELETE FROM table_name :
○ Removes data from the specified table.
● WHERE condition :
○ Restricts deletion to matching records.
Simple Code Example
<?php
$stmt = $conn->prepare("DELETE FROM users WHERE name = ?");
$stmt->bind_param("s", $name);
$name = "Alice";
$stmt->execute();
Notes
● Always use WHERE clauses to specify the records to
delete, preventing unintended deletions.
● Use prepared statements to secure delete
operations.
Warnings
● Be cautious when deleting records, as this action is
irreversible.
● Ensure proper user permissions before allowing
delete operations.
Final Project: "User Management System with
CRUD Operations"
Project Goal
● Create a PHP script that performs basic CRUD
operations (Create, Read, Update, Delete) on a
MySQL database.
● Implement prepared statements for secure database
interactions.
Code for This Project
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "test_db";
// CREATE
if (isset($_POST['create'])) {
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);
$name = $_POST['name'];
$email = $_POST['email'];
$stmt->execute();
echo "New user created successfully.";
}
// READ
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "ID: " . $row["id"] . ", Name: " . $row["name"] . ", Email: " .
$row["email"] . "<br>";
}
} else {
echo "No users found.";
}
// UPDATE
if (isset($_POST['update'])) {
$stmt = $conn->prepare("UPDATE users SET email = ? WHERE name = ?");
$stmt->bind_param("ss", $email, $name);
$name = $_POST['name'];
$email = $_POST['email'];
$stmt->execute();
echo "User updated successfully.";
}
// DELETE
if (isset($_POST['delete'])) {
$stmt = $conn->prepare("DELETE FROM users WHERE name = ?");
$stmt->bind_param("s", $name);
$name = $_POST['name'];
$stmt->execute();
echo "User deleted successfully.";
}
?>