Install PHP 8.3, write your first pages and scripts, and learn the building blocks: variables, decisions, loops and functions.
1
Meet PHP & Setup
10 examples • 4 h
2
Variables, Data Types & Operators
10 examples • 4 h
3
Decisions & Loops
10 examples • 4 h
4
Functions
10 examples • 4 h
🐘
<?php
PHP 8.3 • MySQL • XAMPP
BrainBit Infotech, Ranchi | Complete PHP 8.3 Course | Keys: ← → navigate M menu L Code Lab F fullscreen
M1
Meet PHP & Setup
PHP is the language that runs behind most websites. In this module you install it, write your first lines and see how a browser, a server and PHP work together.
How a website works: browser, server, PHP, database
What PHP is and where it is used
Install XAMPP (PHP 8.3) and VS Code
The <?php tag, echo, print and comments
Run PHP in the terminal and in the browser
Read and fix your first error messages
YOU WILL BUILD: Hello Ranchi pageVisiting card pageCoaching centre "About us" page
🐘
Part 1 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Made by PHP on the serverThe page is the same design for every student. PHP reads roll number 1021 from the URL, gets the marks from MySQL and fills in the table.
🌐
About 70% of websites
W3Techs (August 2026): PHP runs about 70% of websites whose server language is known. WordPress, which runs a huge share of sites, is written in PHP.
🏫
Local work in Jharkhand
School and coaching ERPs, admission and result portals, hospital and shop billing, many state and district websites run on PHP + MySQL.
💼
Jobs and freelancing
PHP, Laravel and WordPress developer jobs are common in Ranchi, Patna, Kolkata and remote. Small businesses need PHP websites every day.
Example 9: Mini "About us" page for a coaching centre
● Hard💼 Real project: Business websites for local institutes
A complete small web page: variables for details, a list of courses printed with a loop, the year calculated by PHP. You will understand the loop fully in Module 3.
about.php
REAL RUN
✍ Try it yourself Add two more courses and a "Contact: 98xxxxxx" line in the header.
Add items inside the [ ] list, separated by commas. The count updates by itself.
● Hard💼 Real project: Debugging: a daily job for every developer
broken.php has two mistakes on purpose: a missing ; and a variable that was never created. PHP stops at the first one and tells you the file and line. fixed.php shows both fixes.
broken.phpfixed.php
REAL RUN
✍ Try it yourself Remove the $marks = 87; line from fixed.php. Which message do you get? Is it an error that stops the program or a warning?
You get "Warning: Undefined variable $marks". A warning does not stop the program; a parse error does.
Every program stores and calculates values: names, marks, prices, dates. Here you learn how PHP stores data, what types exist and how to calculate with them.
Variables and naming rules
Types: string, int, float, bool, null
Quotes, interpolation and heredoc
Constants with define and const
Arithmetic, comparison and logical operators
== vs ===, type juggling and strict_types
YOU WILL BUILD: Electricity billGST invoice lineBike loan EMI calculatorMarksheet
📦
Part 1 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Start with $ then a letter or _. Letters, digits, _ only. Case-sensitive: $Marks and $marks are different. Use clear names: $totalFee not $x.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Concept
The 5 basic data types
Type
Example
Used for
string
"Dhanbad"
names, addresses, messages
int
834001
counts, roll numbers, PIN
float
99.50
prices, percentages
bool
true / false
yes/no: paid? passed?
null
null
"no value yet"
var_dump() shows type and value. It is your best debugging friend. gettype() returns just the type name.
types.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Concept
Strings: quotes, joining and heredoc
Double quotes replace variables: "Hi $name". Use {$a['x']} or {$obj->name} for complex ones.
Single quotes print exactly what you type: 'Hi $name'
. joins strings; .= adds to the end.
\n new line, \t tab, \" a quote (only in double quotes).
Heredoc<<<TXT is for long multi-line text like SMS or emails.
strings.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Concept
Constants: values that never change
A constant is like a variable that can never be changed after it is set. Names are usually UPPER_CASE and have no $.
const GST_RATE = 0.18; at the top level of a file
define('SITE_NAME', 'BrainBit Infotech'); also works (even inside if)
Built-in: PHP_VERSION, PHP_EOL, M_PI, PHP_INT_MAX
In real projectsTax rates, site name, database name, file paths and limits like MAX_UPLOAD_MB are kept as constants in a config.php file.
const.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Concept
Arithmetic and assignment operators
Op
Meaning
Example
+ - * /
add, subtract, multiply, divide
10 / 4 = 2.5
%
remainder (modulus)
17 % 5 = 2
**
power
2 ** 10 = 1024
intdiv()
whole-number division
intdiv(17,5) = 3
+= -= *= /=
update a variable
$t += 50
++ --
add / subtract 1
$count++
Order* / % happen before + -. Use brackets to be clear: ($a + $b) * 2.
math.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Animated explainer
== (loose) vs === (strict) comparison
Expression
==
===
5 vs "5"
true
false
"1" vs "01"
true
false
0 vs "abc"
false (PHP 8)
false
null vs false
true
false
100 vs 100
true
true
== "loose"
Converts types first, then compares values. Convenient but can surprise you.
=== "strict"
Equal only if the value and the type are the same. No conversion.
Rule for this courseAlways use === and !== unless you have a reason not to. Other comparisons: < > <= >= and the spaceship <=> (returns -1, 0 or 1, used for sorting).
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Concept
Logical operators and strict types
Op
True when
&& (and)
both sides are true
|| (or)
at least one side is true
! (not)
flips true/false
Type juggling:"10" + 5 gives 15: PHP converts automatically. declare(strict_types=1); on the first line makes functions refuse wrong types. Professional code uses it; you will see it in Module 4.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 1 of 10 • Easy
Example 1: Student profile variables
● Easy💼 Real project: Student records in a school ERP
Each detail of a student is one variable. var_dump shows the type PHP chose; echo prints a neat profile.
profile.php
REAL RUN
✍ Try it yourself Add $bloodGroup and $village and print them. What type does var_dump show for each?
Both are strings, so var_dump shows string(n) "...", where n is the number of characters.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 2 of 10 • Easy
Example 2: Simple interest
● Easy💼 Real project: Interest on a post office or bank deposit
Simple Interest = P x R x T / 100. Store each value in a variable so the formula reads like maths.
interest.php
REAL RUN
✍ Try it yourself Calculate for Rs 1,20,000 at 6.8% for 5 years.
Change only the three variables at the top. Interest should be 40800.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 3 of 10 • Easy
Example 3: Field area in acres and decimals
● Easy💼 Real project: Land and property calculators
Area = length x width. In Jharkhand land is often measured in decimal (1 decimal = 435.6 sq ft) and acres (1 acre = 100 decimals). round() keeps 2 digits.
land.php
REAL RUN
✍ Try it yourself A plot is 60 ft x 40 ft. How many decimals is it?
2400 / 435.6 = about 5.51 decimals.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 4 of 10 • Easy
Example 4: Rupees to paise and back
● Easy💼 Real project: Payment gateways store money in paise
Payment gateways like Razorpay store amounts as whole paise (int) to avoid decimal errors. intdiv and % split paise back into rupees and paise.
paise.php
REAL RUN
✍ Try it yourself Convert Rs 75.05 to paise. Why do we use round() before (int)?
75.05 * 100 in floating point can be 7504.999...; round makes it 7505 before casting.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 5 of 10 • Easy
Example 5: Temperature converter
● Easy💼 Real project: Weather widgets on news websites
F = C x 9/5 + 32. Brackets and order of operations matter. number_format($x, 1) shows one decimal place.
temp.php
REAL RUN
✍ Try it yourself Convert Ranchi's winter low of 5 C to Fahrenheit.
5 * 9 / 5 + 32 = 41 F.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 6 of 10 • Medium
Example 6: Electricity bill with slabs
● Medium💼 Real project: Utility billing software (like a power company bill)
Units are charged in slabs: the first 100 at one rate, the next 100 at a higher rate, and so on. The rates here are sample practice rates, not the official JBVNL tariff. min() and max() split the units.
bill.php
REAL RUN
✍ Try it yourself Try 80 units and 450 units. Check that the slab numbers always add up to the units.
For 80 units: 80 + 0 + 0. For 450: 100 + 100 + 250.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 7 of 10 • Medium
Example 7: GST invoice line
● Medium💼 Real project: Billing in shops, pharmacies and restaurants
Inside a state, 18% GST is split into CGST 9% + SGST 9%. A constant holds the rate; number_format prints money with 2 decimals.
gst.php
REAL RUN
✍ Try it yourself Change GST to 12% for a medicine item. What are CGST and SGST now?
Set const GST = 12; then each part is 6%.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 8 of 10 • Medium
Example 8: == vs === surprises
● Medium💼 Real project: Avoiding login and search bugs
This shows the real results of the comparisons from the animated slide. A login check with == could treat "01" and "1" as the same user ID, so we use ===.
compare.php
REAL RUN
✍ Try it yourself Add the pair ['abc', 0] and [true, 'yes']. Predict the results first, then run.
'abc' == 0 is false in PHP 8. true == 'yes' is true, because a non-empty string counts as true.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 9 of 10 • Hard
Example 9: Bike loan EMI calculator
● Hard💼 Real project: EMI calculators on bank and showroom websites
EMI = P x r x (1+r)n / ((1+r)n - 1), where r is the monthly rate and n the number of months. ** is the power operator.
emi.php
REAL RUN
✍ Try it yourself Compare 24 months and 36 months. Which has the smaller EMI, and which costs more interest?
36 months: smaller EMI but more total interest. Run twice with $months = 36.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Practice 10 of 10 • Hard
Example 10: Marksheet with percentage and division
● Hard💼 Real project: Result processing in school ERPs
Add marks, calculate the percentage and pick a division with the ternary operator ? : (a short if/else). Full if/else comes in Module 3.
marksheet.php
REAL RUN
✍ Try it yourself Set maths to 30. What changes? Then add a "Distinction" level for 75% or more.
The result becomes FAIL. Put $percent >= 75 ? "Distinction" : ... at the start of the chain.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. What does var_dump(7 / 2); show?
✔ / always gives a float when the result is not whole. Use intdiv() for 3.
Q2. Which prints Hi Ravi when $n = "Ravi"?
✔ Only double quotes replace variables.
Q3. "1" === 1 is ...
✔ === also compares the type: string vs int.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course | Part 1 | Variables, Data Types & Operators
M2Module summary
Recap: Variables, Data Types & Operators
What you learned in M2
✔Variables start with $; = stores a value.
✔Types: string, int, float, bool, null. var_dump shows type and value.
✔Double quotes replace variables; . joins strings; heredoc for long text.
✔Constants (const, define) hold fixed values like GST rates.
● Medium💼 Real project: Grading in CBSE/JAC-style report cards
match(true) checks each condition in order and returns the first arm that is true. Cleaner than a long if/elseif chain. It is wrapped in a small function grade() so we can reuse it; functions are explained fully in Module 4.
grade.php
REAL RUN
✍ Try it yourself Add a check: marks above 100 or below 0 return "Invalid".
Add $m > 100 || $m < 0 => 'Invalid' as the FIRST arm.
● Medium💼 Real project: Menu-driven programs: ATM, IVR, POS machines
A do-while menu shows at least once and repeats until the user chooses Exit. readline() reads what the user types. Below, the answers 1, 2, 500, 1 and 4 were typed into the real program (yellow).
atm.php
REAL RUN
✍ Try it yourself Add option 5 "Mini statement" that prints how many withdrawals were made.
Keep a $count variable; add 1 in case 2 after a successful withdrawal.
A prime has no divisor except 1 and itself. We test divisors only up to the square root and break as soon as one is found. FizzBuzz is the most famous interview warm-up.
prime.php
REAL RUN
✍ Try it yourself Count how many primes are below 1000.
Loop $n from 2 to 999 and increase a counter when $isPrime stays true. Answer: 168.
● Hard💼 Real project: Bus and train booking websites
Real business rules: age decides the base fare, the coach class multiplies it, and a festival discount applies in a date range. match(true), && and a loop over passengers.
fare.php
REAL RUN
✍ Try it yourself Add a rule: students aged 12-25 with a student ID get 25% off. Add a 5th element true/false for the ID.
Destructure [$name, $age, $class, $isStudent] and add an arm before default: $age <= 25 && $isStudent => [...].
A function is a small machine: give it inputs, it gives back a result. Write it once, use it everywhere. Real projects are built from hundreds of small functions.
Define and call functions
Parameters, defaults and named arguments
Type declarations and return types
Union, nullable and variadic parameters
Scope, static variables and references
Closures, arrow functions and recursion
YOU WILL BUILD: GST and discount helpersVisitor counterCategory menu treeReusable validation library
⚙️
Part 1 • about 4 hours 10 practice examples: 5 Easy • 3 Medium • 2 Hard
Functions are the building blocks of every project
VS Code - helpers.php
functionformatRupees(float $amt): string functioncalculateGst(float $amt, float $rate = 18): float functionisValidMobile(string $m): bool functionageFromDob(string $dob): int functionsendFeeReminder(int $studentId): void // used on 40+ pages of the school ERP
♻️
Write once, use everywhere
The same formatRupees() is used on invoices, receipts, reports and emails. Fix a bug in one place, it is fixed everywhere.
🧩
Small and testable
Each function does one job. You can test calculateGst() alone before building the whole billing page.
📚
1000+ built-in functions
PHP already has strlen(), round(), date(), array_sum() ... php.net documents every one with examples.
The returned value replaces the call: $total = addGst(1000) becomes $total = 1180.
Complete PHP 8.3 Course | Part 1 | Functions
M4Concept
Defining and calling functions
function name(params) { ... } defines; name(values) calls.
Names: verbs in camelCase, e.g. calculateFee, isAdult.
return sends a value back. A function without return gives null.
Parameters with a default ($rate = 18) are optional.
Named arguments (PHP 8): book(seats: 2, name: 'Ravi'): order does not matter and the call explains itself.
fn.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Functions
M4Concept
Types: say what goes in and what comes out
Write
Means
int $n
must be an integer
?string $x
string or null (nullable)
int|float $n
union type: either
: void
returns nothing
: bool, : array, : mixed
return type
With declare(strict_types=1); at the top, passing "5" to an int parameter is an error, not a silent conversion. Bugs are caught early. The TypeError below is on purpose.
types.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Functions
M4Animated explainer
Variable scope: inside vs outside a function
global scope (the file)
$city = "Ranchi"
inside showCity()
echo $city; ?
function showCity(string $city) works
Each function has its own box
Variables made outside are not visible inside, and the other way round. This stops functions from breaking each other.
How to get a value in?
Pass it as a parameter (best). global $city; works but makes code hard to follow; avoid it.
static variables
Keep their value between calls of the same function: counters, caches.
Complete PHP 8.3 Course | Part 1 | Functions
M4Concept
Anonymous functions, closures and arrow functions
A function can be stored in a variable: $double = function ($x) { return $x * 2; };
use ($rate) lets a closure see an outside variable.
Arrow functionfn($x) => $x * $rate: one expression, sees outside variables automatically.
Pass them to functions like array_map, usort.
First-class callable (PHP 8.1): strtoupper(...) turns any function into a closure.
closures.php
REAL RUN
Complete PHP 8.3 Course | Part 1 | Functions
M4Animated explainer
Recursion: a function that calls itself
<?php
function fact(int $n): int
{
if ($n <= 1) return 1; // base case
return $n * fact($n - 1);
}
echo fact(4); // 24
The call stack (newest on top):
fact(4) = 4 x ?
fact(3) = 3 x ?
fact(2) = 2 x ?
fact(1) = 1 (base case, stop!)
Real uses: category menus with sub-categories, folder trees, comment replies.
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 1 of 10 • Easy
Example 1: greet() for a welcome screen
● Easy💼 Real project: Dashboards that greet the logged-in user
A function with a default parameter. It picks Good morning/afternoon/evening from the hour, so every page can call greet($name).
greet.php
REAL RUN
✍ Try it yourself Add "Good night" for hours from 22 onward.
Add $hour >= 22 => 'Good night' before the default arm.
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 2 of 10 • Easy
Example 2: Area functions
● Easy💼 Real project: Construction and tiles cost calculators
Small functions, each doing one job. A tile shop calculator uses them to find the floor area and number of tiles.
area.php
REAL RUN
✍ Try it yourself Write triangleArea($base, $height) and use it.
return 0.5 * $base * $height;
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 3 of 10 • Easy
Example 3: Fee with default discount
● Easy💼 Real project: Coaching fee counters
The discount parameter has a default of 0, so most calls stay short. Only special cases pass a discount.
fee.php
REAL RUN
✍ Try it yourself Add a third parameter $registration = 500 that is added to every fee.
Change the return to ... + $registration.
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 4 of 10 • Easy
Example 4: Named arguments for a booking
● Easy💼 Real project: Hotel and event booking forms
With many optional parameters, named arguments make calls readable: you see what each value means and can skip the ones you do not need.
booking.php
REAL RUN
✍ Try it yourself Book for 4 adults, 2 nights, a Suite, with breakfast, using only named arguments.
Functions that return bool usually start with is, has or can. They read like English inside an if.
checks.php
REAL RUN
✍ Try it yourself Write isSeniorCitizen(int $age): bool (60 or above).
return $age >= 60;
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 6 of 10 • Medium
Example 6: Discount with union types
● Medium💼 Real project: E-commerce coupons
The coupon can be a percentage (float) or a flat amount (int). A union type int|float accepts both; is_float tells them apart. ?string allows "no coupon".
coupon.php
REAL RUN
✍ Try it yourself Add a coupon CHHATH15 for 15% off, but give at most Rs 300 discount.
Return [0.15, 300] or check $code === 'CHHATH15' and use min($cart * 0.15, 300).
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 7 of 10 • Medium
Example 7: Visitor counter with static
● Medium💼 Real project: Counting API calls or page hits in one request
A static variable keeps its value between calls. Here a logger numbers each message automatically.
counter.php
REAL RUN
✍ Try it yourself Remove the word static. What happens to the numbers? Why?
Without static, $n starts at 0 on every call, so every line is 001.
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 8 of 10 • Medium
Example 8: Sort by custom closure
● Medium💼 Real project: Sorting product lists by price or rating
usort sorts with your own rule given as a closure; the spaceship <=> compares two items. A variable decides the sort field.
sort.php
REAL RUN
✍ Try it yourself Sort by name A to Z.
sortBy($mobiles, 'name'). The spaceship also compares strings.
Categories contain sub-categories, which contain more. A recursive function prints any depth: it prints one level and calls itself for the children.
menu.php
REAL RUN
✍ Try it yourself Add "Fashion > Men > Kurta" and "Fashion > Women > Saree". Do you need to change the function?
No. Just add the nested array; recursion handles any depth.
Complete PHP 8.3 Course | Part 1 | Functions
M4Practice 10 of 10 • Hard
Example 10: Reusable validation library
● Hard💼 Real project: Form validation used across a whole website
A set of small validators combined by one function. Each rule is a closure in an array, so new rules are easy to add. This is how frameworks like Laravel validate forms.
validate.php
REAL RUN
✍ Try it yourself Add an email rule using filter_var($v, FILTER_VALIDATE_EMAIL).
'email' => fn($v) => filter_var($v, FILTER_VALIDATE_EMAIL) !== false ?: 'must be a valid email'
Complete PHP 8.3 Course | Part 1 | Functions
M4Check your understanding
Quick Quiz
Click an answer. Wrong answers shake; the right one turns green and explains why.
Q1. What does a function return if it has no return?
✔ Mark such functions : void.
Q2. Which is an arrow function?
✔ fn(params) => expression; it sees outside variables automatically.
Q3. Why does a recursive function need a base case?
✔ Without it, calls never end and PHP runs out of memory.
🎯
Your score: 0 / 3 (first try counts)
Answer all questions. Discuss any wrong answer with your partner before moving on.
Complete PHP 8.3 Course | Part 1 | Functions
M4Module summary
Recap: Functions
What you learned in M4
✔function name(params): type { return ...; } builds a reusable machine.
✔Defaults make parameters optional; named arguments make calls clear.