PART 1 of 5  •  about 16 class hours

PHP Foundations

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M1Where is this used in real work?

PHP is behind the websites you use every day

results.dpsranchi.edu.in/result.php?roll=1021
🏫 Class 10 Result 2026PHP
SubjectMarks
Maths92
Science88
English85
Total265 / 300 (88.3%)
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.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Animated explainer

How a website works: browser, server, PHP and database

💻
BrowserChrome on Priya's phone
➤
request
GET /result.php?roll=1021
🖥️
Web serverApache (in XAMPP)
➤
runs
result.php
<?php
PHP 8.3waiting
⇆
SQL query
& rows
🗃️
MySQLstudents, marks tables
HTML page⬅The browser only ever receives plain HTML. It never sees your PHP code.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

PHP in one slide

📜

PHP = "PHP: Hypertext Preprocessor"

A programming language that runs on a server and creates web pages. Started by Rasmus Lerdorf in 1994; free and open source.
⚙️

Server-side

HTML and CSS run in the browser. PHP runs on the server before the page is sent, so it can use databases, files and passwords safely.
🚀

PHP 8.3 (this course)

Released 23 Nov 2023, security support until 31 Dec 2027. Everything you learn here also works in PHP 8.4 and 8.5.

Who uses PHP?

PHP
70.2%
JavaScript
7.2%
Ruby
7.0%
Java
5.5%
ASP.NET
4.2%
Python
1.2%

Share of websites by server-side language (where known). Source: W3Techs, 27 Aug 2026.

Famous PHP softwareWordPress, Moodle (school e-learning), Laravel apps, Magento shops, phpMyAdmin. Facebook was first written in PHP.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

Install your PHP workshop: XAMPP + VS Code

  1. 1
    Download XAMPP for Windows with PHP 8.3 from apachefriends.org. It contains Apache (web server), PHP, MariaDB (MySQL) and phpMyAdmin.
  2. 2
    Install to C:\xampp. Open the XAMPP Control Panel and click Start for Apache and MySQL. Both turn green.
  3. 3
    Add PHP to the Windows PATH: Start menu, "Edit the system environment variables", Path, New, C:\xampp\php. Open a new terminal and type php -v.
  4. 4
    In C:\xampp\php\php.ini set date.timezone = Asia/Kolkata and check display_errors = On (for learning only). Restart Apache.
  5. 5
    Install VS Code + the extension PHP Intelephense. Make the folder D:\php-practice with one sub-folder per module: m01, m02 ...
D:\php-practice\m01> php -v
PHP 8.3.6 (cli) (built: Oct 19 2026 15:16:58) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.3.6, Copyright (c) Zend Technologies
with Zend OPcache v8.3.6, Copyright (c), by Zend Technologies

Real output from the machine that built these slides. Your version number (8.3.x) and date may differ.

📁 C:\xamppXAMPP install
  📁 php php.exe and php.ini
  📁 htdocs web root: http://localhost/
  📁 mysql the database server
📁 D:\php-practiceyour practice files
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Animated explainer

Two ways to run PHP: terminal and browser

⌨ 1. Command line (CLI)

D:\php-practice\m01> php hello.php
Johar Ranchi!
Output goes straight to the terminal. Great for learning, scripts, reports, cron jobs. Most examples in Part 1 and 2 use this.

🌐 2. Web (browser)

D:\php-practice\m01> php -S localhost:8000
PHP Development Server (http://localhost:8000) started
localhost:8000/hello.php
Johar Ranchi!
Or with XAMPP: put files in C:\xampp\htdocs\php-practice and open http://localhost/php-practice/hello.php.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

Your first PHP file

A PHP file ends with .php. PHP code goes between <?php and ?>.

  • echo prints text. "\n" means "new line".
  • Every statement ends with a semicolon ;
  • In a file that is only PHP, leave out the closing ?> (it avoids stray spaces).
  • print also prints, but echo is used more.
Most common beginner errorForgetting ; at the end. PHP then says syntax error, unexpected ... on the next line.
hello.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

Comments: notes for humans

Comments are ignored by PHP. Use them to explain why code exists, or to switch a line off while testing.

StyleUse
// textone-line comment (most common)
# textalso one line (shell style)
/* ... */many lines
/** ... */DocBlock: describes a function for VS Code
Good habitWrite comments for your teammate who will read this code six months later. That teammate is often you.
comments.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

Mixing PHP and HTML

PHP's superpower: put PHP inside an HTML page. Everything outside <?php ?> is sent to the browser as it is.

  • <?= $x ?> is a short way to write <?php echo $x; ?>
  • date('d M Y') gives today's date
  • The browser receives only the final HTML. Right-click, View page source shows no PHP.
Look at the Request tabIt shows the exact HTML the server sent. No PHP code is there.
today.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Concept

Variables in 30 seconds (you need them from Example 1)

A variable is a named box that stores a value. In PHP every variable name starts with $.

<?php
$name = "Aman";        // text goes in quotes
$age  = 16;            // numbers without quotes
echo "Hi $name, you are $age years old.\n";
  • Inside double quotes PHP replaces $name with its value.
  • The dot . joins strings: "Hi " . $name
  • Full details in Module 2.
📦
$name
"Aman"
📦
$age
16
Hi Aman, you are 16 years old.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 1 of 10  •  Easy

Example 1: Hello Ranchi page

● Easy💼 Real project: The first page of any website
A web page made by PHP. The HTML is fixed; PHP adds the greeting and the year. Run it with php -S localhost:8000 and open /index.php.
index.php
REAL RUN
✍ Try it yourself Add a line that shows your own name and your school using echo.
Inside <body> write <p><?php echo "Name: Riya"; ?></p>.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 2 of 10  •  Easy

Example 2: Shop sign board with echo

● Easy💼 Real project: Printing text in billing and shop software
echo can print several pieces separated by commas, and . joins text. str_repeat draws a line of characters.
shop.php
REAL RUN
✍ Try it yourself Change the shop name to your favourite local shop and add a line "Closed on Tuesday".
Copy one echo line and change the text inside the quotes.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 3 of 10  •  Easy

Example 3: Comments in a fee script

● Easy💼 Real project: Readable code in a coaching office project
Good comments explain each step. A teammate can understand the fee calculation without asking you.
fee.php
REAL RUN
✍ Try it yourself Change the duration to 6 months. What is the monthly fee now? Add a comment that explains the change.
12000 / 6 = 2000. Write // changed to 6 months for the new batch.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 4 of 10  •  Easy

Example 4: Today's date on a page

● Easy💼 Real project: Dates on notices, bills and dashboards
date() formats the current date and time. The letters mean: d day, m month, Y year, l weekday, h:i A time.
date.php
REAL RUN
✍ Try it yourself Print the date in the format 25/11/2026 (with slashes).
Use date('d/m/Y').
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 5 of 10  •  Easy

Example 5: PHP version and server info

● Easy💼 Real project: Checking a hosting server before you deploy
Before uploading a project to hosting, developers check the PHP version and settings. PHP has ready-made constants and functions for this.
info.php
REAL RUN
✍ Try it yourself Create phpinfo.php with <?php phpinfo(); and open it in the browser. Find "date.timezone".
phpinfo() prints a long HTML page with every setting. Delete that file before going live: it reveals server details.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 6 of 10  •  Medium

Example 6: Visiting card page

● Medium💼 Real project: Personal and business profile pages
Store the details in variables once, then use them inside HTML with <?= ?>. Change a variable and the whole card updates.
card.php
REAL RUN
✍ Try it yourself Make a visiting card for your father, mother or a local shop. Add a website line.
Add $website = "www.example.in"; at the top and <br>🌐 <?= $website ?> in the card.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 7 of 10  •  Medium

Example 7: Mixing HTML and PHP: school notice

● Medium💼 Real project: Notice boards on school websites
A notice page that changes its message by itself. PHP checks the weekday: on Sunday it shows "School closed", on other days the timing.
notice.php
REAL RUN
✍ Try it yourself Add a second check: on Saturday show "Half day: 8:00 AM to 11:30 AM".
Use <?php elseif ($day === 'Saturday'): ?> between the if and the else.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 8 of 10  •  Medium

Example 8: Command-line welcome script

● Medium💼 Real project: Small office tools run from the terminal
Command-line scripts can read words typed after the file name. $argv is the list of those words; $argv[1] is the first one.
welcome.php
REAL RUN
✍ Try it yourself Run it with your own name and city. What happens if you give no name at all?
php welcome.php Neha Dhanbad. With no name, ?? uses the default "Student".
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 9 of 10  •  Hard

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.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Practice 10 of 10  •  Hard

Example 10: Reading and fixing your first errors

● 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.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M1Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. Where does PHP code run?
✔ The browser only receives the finished HTML.
Q2. Which line is correct PHP?
✔ Every statement ends with a semicolon.
Q3. What does php -S localhost:8000 do?
✔ Then open http://localhost:8000/file.php in the browser.
🎯
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  |  Meet PHP & Setup
M1Module summary

Recap: Meet PHP & Setup

What you learned in M1

  • ✔A browser sends a request; the server runs PHP; PHP may ask MySQL; HTML comes back.
  • ✔XAMPP gives you Apache, PHP 8.3, MariaDB (MySQL) and phpMyAdmin on Windows.
  • ✔PHP code lives inside <?php ... ?>; statements end with ;
  • ✔echo prints; <?= $x ?> prints inside HTML.
  • ✔Run with php file.php (terminal) or php -S localhost:8000 (browser).
  • ✔Error messages tell you the file and line. Read them calmly and fix one at a time.
🏆

Module 1 complete!

You practised 10 real examples.

👉 Coming next

M2 Variables, Data Types & Operators: store marks, prices and names, and calculate bills, GST and EMIs.
Complete PHP 8.3 Course  |  Part 1  |  Meet PHP & Setup
M2

Variables, Data Types & Operators

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M2Where is this used in real work?

Every bill, marksheet and invoice is variables + operators

billing.sharmaelectronics.in/invoice.php?no=245
Sharma Electronics, Main Road, RanchiPHP
ItemQtyRateAmount
LED Bulb 9W4120.00480.00
Extension board1350.00350.00
CGST 9% + SGST 9%149.40
Total979.40
Behind the screen$qty * $rate, $subtotal * 0.18, round($total, 2): just variables and operators.
🧾

Billing and GST

Shops, pharmacies and restaurants calculate totals, tax and discounts with arithmetic operators.
🎓

Results and grades

Schools add marks, find percentages and compare them to cut-offs with comparison operators.
🏦

Loans and EMIs

Banks, NBFCs and bike showrooms show EMI calculators written with formulas like the one in Example 9.
Complete PHP 8.3 Course  |  Part 1  |  Variables, Data Types & Operators
M2Animated explainer

A variable is a labelled box in memory

<?php
$student = "Priya Kumari";
$marks = 82;
$marks = $marks + 5;
$passed = true;
📦
$student
"Priya Kumari"
string
📦
$marks
82
int
📦
$passed
true
bool

Naming rules

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

TypeExampleUsed for
string"Dhanbad"names, addresses, messages
int834001counts, roll numbers, PIN
float99.50prices, percentages
booltrue / falseyes/no: paid? passed?
nullnull"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

OpMeaningExample
+ - * /add, subtract, multiply, divide10 / 4 = 2.5
%remainder (modulus)17 % 5 = 2
**power2 ** 10 = 1024
intdiv()whole-number divisionintdiv(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"truefalse
"1" vs "01"truefalse
0 vs "abc"false (PHP 8)false
null vs falsetruefalse
100 vs 100truetrue

== "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

OpTrue 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.

Casting: (int) "42 students" gives 42, (float), (string), (bool).

logic.php
REAL RUN
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.
  • ✔Arithmetic + - * / % **, intdiv, and shortcuts += ++.
  • ✔Prefer ===; use && || ! to combine conditions.
🏆

Module 2 complete!

You practised 10 real examples.

👉 Coming next

M3 Decisions & Loops: if/else, match, and loops that print tables, menus and patterns.
Complete PHP 8.3 Course  |  Part 1  |  Variables, Data Types & Operators
M3

Decisions & Loops

Programs must choose (pass or fail? cash or UPI?) and repeat (print 40 students, try PIN 3 times). Decisions and loops make that possible.

  • if, elseif, else and nested conditions
  • switch and the modern match expression
  • Ternary ?: and null coalescing ??
  • while, do-while, for and foreach loops
  • break and continue
  • Alternative syntax for HTML templates
YOU WILL BUILD:
Grade calculatorATM menuTicket fare enginePrime number finder
🚦
Part 1  •  about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M3Where is this used in real work?

Decisions and loops run every real application

irctc-like.example/fare.php
🚆 Ranchi → Patna (Jan Shatabdi)PHP
PassengerAgeRule appliedFare
Ravi42AdultRs 255
Sita63Senior: 40% offRs 153
Golu4Child under 5: freeRs 0
Behind the screenA loop goes through each passenger; if / match picks the rule for each one.
🚦

Rules and decisions

Discounts, fines, grades, access rights, shipping charges: every business rule is an if or a match.
🔁

Repeating work

Printing every row of a report, sending SMS to every parent, retrying a payment: loops.
🔐

Menus and limits

ATM and IVR menus repeat until you choose Exit; a login allows only 3 tries.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Animated explainer

if / elseif / else: a decision flowchart

<?php
$marks = 72;
if ($marks >= 90) {
    echo "Grade A+";
} elseif ($marks >= 60) {
    echo "Grade A";
} elseif ($marks >= 33) {
    echo "Grade B";
} else {
    echo "Fail";
}
$marks = 72
↓
72 >= 90 ? ...
↓
72 >= 60 ? ...
🎉 prints "Grade A"
The rest (>= 33 and else) is skipped. Only one block ever runs.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Concept

if, elseif, else and nested conditions

  • The condition goes in ( ), the code in { }.
  • elseif adds more choices; else is "everything else".
  • Combine tests with && and ||.
  • An if inside an if is a nested condition. Keep nesting shallow; it gets hard to read.
Truthy and falsy0, "", "0", null, [] and false count as false in an if. Everything else is true.
admission.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Concept

match: the modern switch (PHP 8)

match compares a value with each arm using === and returns a result. No break needed.

switchmatch
loose ==strict ===
needs breakno fall-through
a statementan expression (gives a value)
no match: nothingno match: UnhandledMatchError

match(true) lets each arm be a condition, perfect for ranges like grades.

match.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Concept

Short forms: ternary ?: and null coalescing ??

  • cond ? a : b gives a if cond is true, else b. Good for one-line choices.
  • $x ?? 'default' gives $x if it exists and is not null, else the default. Perfect for missing form fields or URL values.
  • $x ??= 'default' sets $x only if it is null or missing.
  • a ?: b (Elvis) gives a if a is truthy, else b.
Don't chain ternariesPHP 8 makes a ? b : c ? d : e an error without brackets. Use match instead.
short.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Animated explainer

How a for loop works

<?php
for ($i = 1; $i <= 3; $i++) {
    echo "5 x $i = " . 5 * $i . "\n";
}
echo "Done\n";

1. Start

$i = 1 runs once

2. Check

$i <= 3 before each round

3. Step

$i++ after each round
$i = ?
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
Done
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Concept

while, do-while, foreach, break and continue

LoopUse when
foryou know how many times
whilerepeat while a condition is true
do-whilerun at least once (menus)
foreachgo through every item of an array (most used!)

break leaves the loop; continue skips to the next round.

Infinite loopIf the condition never becomes false, the loop never ends. Press Ctrl+C to stop a script.
loops.php
REAL RUN
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 1 of 10  •  Easy

Example 1: Pass or fail

● Easy💼 Real project: Result processing
The simplest decision: one condition, two outcomes. The pass mark is a constant so it can be changed in one place.
result.php
REAL RUN
✍ Try it yourself Add two students of your own. Change PASS_MARK to 40 and run again.
Only the const line needs to change; every check uses it.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 2 of 10  •  Easy

Example 2: Even or odd

● Easy💼 Real project: Alternate row colours, odd/even house numbers
The remainder of dividing by 2 tells even (0) from odd (1). Websites use this to colour alternate table rows.
evenodd.php
REAL RUN
✍ Try it yourself Print only the multiples of 3 between 1 and 30.
Use if ($n % 3 === 0) inside a loop from 1 to 30.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 3 of 10  •  Easy

Example 3: Multiplication table

● Easy💼 Real project: Learning apps for primary students
A for loop prints a table. str_pad lines the numbers up neatly.
table.php
REAL RUN
✍ Try it yourself Run php table.php 23. Then print tables from 2 to 5 using a loop inside a loop.
Wrap the for loop in another: for ($t = 2; $t <= 5; $t++) { ... use $t ... }
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 4 of 10  •  Easy

Example 4: Day name with match

● Easy💼 Real project: Opening hours on shop and clinic websites
date('N') gives the weekday as 1 (Monday) to 7 (Sunday). match turns it into opening hours for a clinic.
clinic.php
REAL RUN
✍ Try it yourself Add a holiday rule: day number 8 does not exist. What happens without a default arm? Try it.
match(8) without default throws UnhandledMatchError. That is safer than silently doing nothing.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 5 of 10  •  Easy

Example 5: Countdown

● Easy💼 Real project: Launch timers, OTP expiry, exam timers
A while loop counting down. usleep() pauses in microseconds (here 0.2 s) so you see it tick in the terminal.
countdown.php
REAL RUN
✍ Try it yourself Change it to count down by 2 (10, 8, 6 ...).
Start at 10 and use $seconds -= 2.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 6 of 10  •  Medium

Example 6: Grade calculator with match(true)

● 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.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 7 of 10  •  Medium

Example 7: ATM menu loop

● 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.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 8 of 10  •  Medium

Example 8: Number patterns

● Medium💼 Real project: Logic building (asked in every interview)
A loop inside a loop: the outer loop picks the row, the inner loop prints the items of that row. This is how tables and grids are printed.
pattern.php
REAL RUN
✍ Try it yourself Print the triangle upside down (5 stars first).
Make the outer loop go from $rows down to 1: for ($r = $rows; $r >= 1; $r--).
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 9 of 10  •  Hard

Example 9: Prime numbers and FizzBuzz

● Hard💼 Real project: Quiz apps and coding tests
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.
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Practice 10 of 10  •  Hard

Example 10: Ticket fare engine

● 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 => [...].
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M3Check your understanding

Quick Quiz

Click an answer. Wrong answers shake; the right one turns green and explains why.

Q1. How many times does for ($i = 0; $i < 5; $i++) run?
✔ 0, 1, 2, 3, 4: five times.
Q2. What does $_GET['city'] ?? 'Ranchi' give if city was not sent?
✔ ?? returns the right side when the left is missing or null.
Q3. Which loop always runs at least once?
✔ The condition is checked at the end. Perfect for menus.
🎯
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  |  Decisions & Loops
M3Module summary

Recap: Decisions & Loops

What you learned in M3

  • ✔if / elseif / else runs only the first block whose condition is true.
  • ✔match is strict, returns a value and has no fall-through; match(true) handles ranges.
  • ✔? : for short choices, ?? for safe defaults.
  • ✔for when you know the count, while for conditions, do-while for menus.
  • ✔foreach walks through arrays; break exits, continue skips.
  • ✔Nested loops print tables, grids and patterns.
🏆

Module 3 complete!

You practised 10 real examples.

👉 Coming next

M4 Functions: package your logic into reusable machines like calculateGST() and isValidMobile().
Complete PHP 8.3 Course  |  Part 1  |  Decisions & Loops
M4

Functions

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
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M4Where is this used in real work?

Functions are the building blocks of every project

VS Code - helpers.php
function formatRupees(float $amt): string
function calculateGst(float $amt, float $rate = 18): float
function isValidMobile(string $m): bool
function ageFromDob(string $dob): int
function sendFeeReminder(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.
Complete PHP 8.3 Course  |  Part 1  |  Functions
M4Animated explainer

A function is a machine: input, work, output

<?php
function addGst(float $price, float $rate = 18): float
{
    $tax = $price * $rate / 100;
    return $price + $tax;
}

$total = addGst(1000);
echo $total;   // 1180
inputs$price = 1000
$rate = 18
➤
⚙️
addGst()working...
➤
return1180
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

WriteMeans
int $nmust be an integer
?string $xstring or null (nullable)
int|float $nunion type: either
: voidreturns nothing
: bool, : array, : mixedreturn 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 function fn($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.
bookRoom(guest: 'X', checkIn: '...', nights: 2, adults: 4, breakfast: true, room: 'Suite')
Complete PHP 8.3 Course  |  Part 1  |  Functions
M4Practice 5 of 10  •  Easy

Example 5: isAdult() and other yes/no helpers

● Easy💼 Real project: Eligibility checks on forms
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.
Complete PHP 8.3 Course  |  Part 1  |  Functions
M4Practice 9 of 10  •  Hard

Example 9: Recursive category menu

● Hard💼 Real project: Shop menus: Electronics > Mobiles > Android
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.
  • ✔Types (int, ?string, int|float, void) + strict_types catch bugs early.
  • ✔Variables inside a function are private; pass values in as parameters. static remembers between calls.
  • ✔Closures with use, arrow functions fn and strtoupper(...) pass behaviour around.
  • ✔Recursion solves tree problems; always include a base case.
🏆

Module 4 complete!

You practised 10 real examples.

👉 Coming next

Part 2, M5 Arrays: lists, key-value records, sorting, filtering and the 70+ array functions.
Complete PHP 8.3 Course  |  Part 1  |  Functions
1 / 1

✎ Code Lab