PART 2 of 5  •  about 17 class hours

Working with Data

Arrays, strings, regular expressions, dates, JSON and files: the tools for handling real data like marks, bills and reports.

5

Arrays

10 examples  •  4 h
6

Strings & Regular Expressions

10 examples  •  5 h
7

Dates, Maths & JSON

10 examples  •  4 h
8

Files & Directories

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
M5

Arrays

An array holds many values in one variable: a class list, a price list, a cart, a whole table of students. Arrays are the most used data structure in PHP.

  • Indexed arrays (lists)
  • Associative arrays (key => value)
  • Multidimensional arrays (tables)
  • Add, remove, search and count
  • Sorting: sort, asort, ksort, usort
  • array_map, array_filter, array_reduce, destructuring and spread
YOU WILL BUILD:
Shopping cart totalStudents grouped by cityTop 3 rankersInventory with low-stock alerts
🗂️
Part 2  •  about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M5Where is this used in real work?

Arrays hold the data of every page you see

shop.example.in/cart.php
🛒 Your Cart (3 items)PHP
ItemQtyPrice
Aashirvaad Atta 5kg2Rs 560
Tata Salt 1kg1Rs 28
Mustard Oil 1L1Rs 165
$cart = [
  ['name' => 'Aashirvaad Atta 5kg', 'qty' => 2, 'price' => 280],
  ['name' => 'Tata Salt 1kg', 'qty' => 1, 'price' => 28], ...];
🛒

Carts and orders

Every e-commerce cart is an array of items, each item an array of name, qty and price.
📊

Database results

When PHP reads rows from MySQL, you get an array of rows. Every table on a website is printed from an array.
📝

Forms and JSON

Form data ($_POST), JSON from APIs and settings files all arrive as arrays.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Animated explainer

Indexed vs associative arrays

Indexed: positions 0, 1, 2 ...

$cities = ['Ranchi', 'Gaya', 'Dhanbad'];
index 0Ranchi
index 1Gaya
index 2Dhanbad
index 3Bokaro
echo $cities[0]; // Ranchi
$cities[] = 'Bokaro'; // adds at the end

Associative: named keys

$student = ['name' => 'Asha', 'roll' => 21];
'name'➤Asha
'roll'➤21
'city'➤Hazaribagh
echo $student['name']; // Asha
$student['city'] = 'Hazaribagh';
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Concept

Creating, reading and changing arrays

  • Create with [ ] (old style: array()).
  • count($a) number of items; print_r($a) shows the whole array.
  • array_push / $a[] = add at end; array_pop removes from end.
  • array_unshift / array_shift: add/remove at the start.
  • unset($a['key']) removes one item.
  • in_array, array_search, array_key_exists, isset to search.
basics.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Concept

Multidimensional arrays: a table in PHP

An array can contain arrays. A list of associative arrays is exactly like a database table: each inner array is a row.

  • $students[1]['name']: row 1, column "name"
  • foreach ($students as $s) gives one row at a time
  • array_column($students, 'marks') pulls out one column
You will see this shape everywherePDO's fetchAll() in Module 16 returns exactly this kind of array.
table.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Concept

Sorting arrays

FunctionSorts byKeeps keys?
sort / rsortvalue, up / downno (re-numbers)
asort / arsortvalue, up / downyes
ksort / krsortkeyyes
usortyour own ruleno
CarefulSort functions change the array itself and return true, not the sorted array. $x = sort($a); is a common mistake.
sorting.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Animated explainer

map, filter, reduce: three power tools

🔄 array_map

change every item
100250400
↓ fn($p) => $p * 1.18
118295472

🔍 array_filter

keep only items that pass a test
45289112
↓ fn($m) => $m >= 33
4591

➕ array_reduce

combine all items into one value
56028165
↓ fn($sum, $x) => $sum + $x
753
Why use them?They replace 5-line foreach loops with one clear line. You will see them in every modern PHP and Laravel project.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Concept

Destructuring, spread and handy helpers

  • Destructuring: [$a, $b] = [1, 2]; or ['name' => $n] = $row;
  • Swap in one line: [$a, $b] = [$b, $a];
  • Spread ... joins arrays: [...$a, ...$b]
  • array_slice part of an array; array_unique remove duplicates
  • array_combine keys + values; array_flip; range(1, 10)
  • implode array to string; explode string to array
helpers.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 1 of 10  •  Easy

Example 1: Class list

● Easy💼 Real project: Attendance registers
An indexed array of names. foreach with $i => $name gives the position and the value, so we can print roll numbers.
classlist.php
REAL RUN
✍ Try it yourself Sort the list alphabetically before printing, and print the total again.
Call sort($class); before the foreach loop.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 2 of 10  •  Easy

Example 2: Price list

● Easy💼 Real project: Menu cards and rate lists
An associative array maps each item to its price. number_format and str_pad make a neat menu card.
menu.php
REAL RUN
✍ Try it yourself Add "Rugra Curry" at Rs 120 and print only items under Rs 50.
Inside foreach: if ($price < 50) echo ...
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 3 of 10  •  Easy

Example 3: Count and search

● Easy💼 Real project: Searching a list of registered users
in_array answers yes/no; array_search returns the position; array_count_values counts how many times each value appears.
search.php
REAL RUN
✍ Try it yourself Find which food got the most votes and print it.
$counts = array_count_values($votes); arsort($counts); echo array_key_first($counts);
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 4 of 10  •  Easy

Example 4: Sort marks

● Easy💼 Real project: Merit lists
arsort sorts by value high to low and keeps the names attached. array_key_first gives the topper.
merit.php
REAL RUN
✍ Try it yourself Rohit and Tanya have equal marks. Make ties show the same rank.
Keep $prev; increase $rank only when $m !== $prev (use $i + 1 as rank for "1,1,3" style).
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 5 of 10  •  Easy

Example 5: Phone book

● Easy💼 Real project: Contacts in CRM and school apps
An associative array where the key is the name. ksort keeps the phone book in A to Z order; isset checks if a contact exists.
phonebook.php
REAL RUN
✍ Try it yourself Search for a name that does not exist. Then add "Police - 112".
Change $find. Add $book['Police'] = '112';
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 6 of 10  •  Medium

Example 6: Shopping cart total

● Medium💼 Real project: E-commerce checkout
A cart is a list of items. array_map calculates each line total, array_sum adds them. Delivery is free above Rs 499.
cart.php
REAL RUN
✍ Try it yourself Remove the atta from the cart. Is delivery still free?
unset($cart[0]) before calculating. Subtotal becomes 193, so delivery is Rs 40.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 7 of 10  •  Medium

Example 7: Group students by city

● Medium💼 Real project: Reports grouped by branch or district
Build a new array where each key is a city and the value is the list of students there. This "group by" pattern is used in almost every report.
group.php
REAL RUN
✍ Try it yourself Add a "marks" field and print the average marks per city.
Group marks the same way: $byCity[$s['city']][] = $s['marks']; then array_sum / count.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 8 of 10  •  Medium

Example 8: Top 3 rankers with usort

● Medium💼 Real project: Leaderboards in quiz and coding apps
usort sorts rows by marks (high first) and, for ties, by name. array_slice takes the first 3.
top3.php
REAL RUN
✍ Try it yourself Explain why Tanya is ranked above Rohit.
Same marks, so the second rule compares time: less time wins. [$b, $a] vs [$a, $b] order flips the direction.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 9 of 10  •  Hard

Example 9: Sales report from nested arrays

● Hard💼 Real project: Monthly sales dashboards
Nested data: branches, each with monthly sales. We calculate totals per branch and per month with array_sum, array_column and array_map, and draw a text bar chart.
sales.php
REAL RUN
✍ Try it yourself Find the month with the highest total, and the growth % from Aug to Nov for each branch.
Growth = ($s['Nov'] - $s['Aug']) / $s['Aug'] * 100.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Practice 10 of 10  •  Hard

Example 10: Inventory with low-stock alerts

● Hard💼 Real project: Stock management for medical and grocery stores
A medical store inventory. array_filter finds items below their reorder level, array_reduce finds total stock value, and expiry dates are compared as strings (YYYY-MM-DD sorts correctly).
inventory.php
REAL RUN
✍ Try it yourself Add 2 new medicines, one of them already expired. Print "EXPIRED" items separately.
Filter with $s['expiry'] < $today for expired, and <= today+60 days for expiring soon.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M5Check your understanding

Quick Quiz

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

Q1. What does $a = ['x', 'y']; echo $a[1]; print?
✔ Indexes start at 0, so [1] is the second item.
Q2. Which keeps the keys while sorting by value?
✔ asort / arsort keep key-value pairs together.
Q3. Which function keeps only items that pass a test?
✔ filter chooses; map transforms; reduce summarises.
🎯
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 2  |  Arrays
M5Module summary

Recap: Arrays

What you learned in M5

  • ✔Indexed arrays start at 0; associative arrays use your own keys.
  • ✔A list of associative arrays is a table (like database rows).
  • ✔count, in_array, array_search, isset, unset for everyday work.
  • ✔sort/rsort (re-number), asort/arsort (keep keys), ksort (by key), usort (your rule).
  • ✔array_map transforms, array_filter chooses, array_reduce summarises.
  • ✔Destructuring [$a, $b] = ... and spread [...$a, ...$b].
🏆

Module 5 complete!

You practised 10 real examples.

👉 Coming next

M6 Strings & Regular Expressions: format names, mask mobile numbers, Indian rupee format and validate PIN codes.
Complete PHP 8.3 Course  |  Part 2  |  Arrays
M6

Strings & Regular Expressions

Most data on the web is text: names, addresses, messages, codes. PHP has hundreds of string functions, plus regular expressions for checking and extracting patterns.

  • Length, case, trim, search and replace
  • substr, explode, implode, str_pad
  • Multibyte strings: Hindi text with mb_*
  • sprintf, number_format and Indian lakh/crore format
  • Regular expressions: preg_match, preg_replace, preg_split
  • Validating mobile numbers, PIN codes, emails
YOU WILL BUILD:
Mobile number maskingURL slug makerStrong password checkerBank SMS parser
🔤
Part 2  •  about 5 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M6Where is this used in real work?

Text processing is everywhere

bank.example.in/account.php
Welcome, Sunita DeviPHP
Mobile98******45masked with substr + str_repeat
Balance₹12,45,600.50Indian lakh format
Blog URL/blog/chhath-puja-2026-guideslug with preg_replace
PIN834001 ✔checked with a regex
🔒

Privacy

Banks and apps show only part of a mobile or account number. That is substr() and str_repeat().
✅

Validation

Every form checks mobile numbers, PIN codes, PAN-style IDs and emails with regular expressions.
📰

SEO and content

Blogs and shops turn titles into clean URLs and short summaries automatically.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Concept

Everyday string functions

FunctionDoes
strlennumber of bytes (characters for English)
strtoupper / strtolower / ucwords / ucfirstchange case
trim / ltrim / rtrimremove spaces at the ends
str_contains / str_starts_with / str_ends_withPHP 8 yes/no checks
strposposition of a piece (or false)
str_replacereplace text
substr($s, start, length)cut a part
str_pad, str_repeat, strrev, wordwrapformat
strfn.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Concept

explode, implode and Hindi text (mb_*)

  • explode(',', $csv) splits a string into an array.
  • implode(', ', $arr) joins an array into a string.
  • Hindi, Bengali and emoji use several bytes per character. strlen counts bytes; mb_strlen counts real characters.
  • Always use mb_substr, mb_strtoupper for non-English text. PHP 8.3 adds mb_str_pad.
XAMPPmbstring is on by default. Save files as UTF-8 in VS Code (bottom-right of the window).
mb.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Concept

sprintf and money formats (incl. lakh/crore)

  • sprintf / printf: a template with placeholders: %s text, %d integer, %.2f 2 decimals, %05d pad with zeros, %-10s left-align.
  • number_format(1234567.5, 2) gives the western 1,234,567.50
  • India groups as 12,34,567.50. Use the intl extension's NumberFormatter('en_IN', ...) (enable extension=intl in php.ini) or write a small function (Example 6).
money.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Animated explainer

Reading a regular expression

/^[6-9]\d{9}$/

^ start

the match must begin at the very start

[6-9]

one character from 6 to 9 (Indian mobiles start with 6-9)

\d{9}

\d = a digit, {9} = exactly 9 times

$ end

nothing allowed after the 9 digits
9835012345 ✔5835012345 ✘98350 12345 ✘983501234 ✘
More symbols+ one or more, * zero or more, ? optional, \w letter/digit/_, \s space, ( ) capture a group, | or, i after the last / = ignore case.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Concept

preg_match, preg_match_all, preg_replace, preg_split

FunctionReturns
preg_match($re, $s, $m)1 if found (first match in $m), else 0
preg_match_allcount of all matches
preg_replace($re, $new, $s)the changed string
preg_split($re, $s)array split by the pattern

Groups ( ) capture parts: $m[1], $m[2]. Named groups (?<year>\d{4}) appear as $m['year'].

regex.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 1 of 10  •  Easy

Example 1: Name formatter

● Easy💼 Real project: Cleaning names typed into forms
People type names in any case with extra spaces. trim, preg_replace (collapse spaces) and ucwords(strtolower()) make them neat before saving.
names.php
REAL RUN
✍ Try it yourself Also produce a "SURNAME, First" version, e.g. "MAHTO, Suresh Kumar".
Use explode(' ', $clean), array_pop for the surname, implode the rest.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 2 of 10  •  Easy

Example 2: Count words in feedback

● Easy💼 Real project: Feedback and review analysis
str_word_count counts words, substr_count counts a phrase, and stripos searches ignoring case.
feedback.php
REAL RUN
✍ Try it yourself Count how many sentences there are (they end with . or !).
preg_match_all('/[.!?]/', $feedback) returns the count.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 3 of 10  •  Easy

Example 3: Mask a mobile number

● Easy💼 Real project: OTP screens and order pages
Show only the first 2 and last 2 digits. substr with a negative start counts from the end; str_repeat makes the stars.
mask.php
REAL RUN
✍ Try it yourself Mask a 12-digit Aadhaar-style number to show only the last 4 digits: XXXX XXXX 1234.
'XXXX XXXX ' . substr($n, -4)
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 4 of 10  •  Easy

Example 4: Slug for a blog URL

● Easy💼 Real project: SEO-friendly URLs on blogs and shops
A slug turns "Chhath Puja 2026: Complete Guide!" into chhath-puja-2026-complete-guide. Lowercase, then replace anything that is not a letter or digit with a hyphen.
slug.php
REAL RUN
✍ Try it yourself Add a maximum length of 40 characters without cutting a word in half.
Use wordwrap($s, 40, "\n") or cut with substr and then remove the last partial piece after the final hyphen.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 5 of 10  •  Easy

Example 5: Initials from a full name

● Easy💼 Real project: Avatar circles in apps
Apps show a coloured circle with initials when there is no photo. explode the name, take the first letter of each word with array_map.
initials.php
REAL RUN
✍ Try it yourself Use the first and LAST word instead of the first two (Ravi Shankar Prasad -> RP).
Take $letters[0] . end($letters) when there is more than one word.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 6 of 10  •  Medium

Example 6: Indian rupee format (lakh/crore)

● Medium💼 Real project: Invoices, salary slips and property sites
Indian grouping: last 3 digits, then groups of 2. Our own function handles decimals and negative numbers; we also convert big numbers to words like "1.25 crore".
inr.php
REAL RUN
✍ Try it yourself Add a parameter so inr() can print without "Rs " (for spreadsheets).
Add bool $symbol = true and use ($symbol ? 'Rs ' : '').
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 7 of 10  •  Medium

Example 7: Mobile, PIN and email validator

● Medium💼 Real project: Registration and admission forms
Each field has a pattern. One function returns a list of problems, so the form can show them all at once.
check.php
REAL RUN
✍ Try it yourself Accept mobiles written with +91 or 0 in front, like +919835012345.
Allow an optional prefix: '/^(\+91|0)?[6-9]\d{9}$/'.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 8 of 10  •  Medium

Example 8: Template messages with placeholders

● Medium💼 Real project: Bulk SMS and WhatsApp reminders
Messages are stored with placeholders like {name}. strtr replaces all of them in one go, so the office staff can edit templates without touching code.
sms.php
REAL RUN
✍ Try it yourself Add a {mobile} placeholder that shows a masked mobile number.
Reuse maskMobile() from Example 3 inside the strtr array.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 9 of 10  •  Hard

Example 9: Strong password checker

● Hard💼 Real project: Sign-up pages and admin panels
Several regex tests give a score and specific tips. Real sites (banks, government portals) apply similar rules. We never print or store the password itself.
password.php
REAL RUN
✍ Try it yourself Add a rule: the password must not contain the user's name (case-insensitive).
Pass $name too and add 'not your name' => stripos($p, $name) === false.
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Practice 10 of 10  •  Hard

Example 10: Parse a bank SMS

● Hard💼 Real project: Expense tracker apps that read bank alerts
Expense apps read bank SMS and pull out the amount, type, account, date and balance with one regex with named groups. The SMS texts here are sample messages written for practice.
parsesms.php
REAL RUN
✍ Try it yourself Add a category: if "to" contains zomato or swiggy it is Food, if it has "SALARY" it is Income, else Other.
Use match(true) with str_contains(strtolower($m['to']), 'zomato') ...
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M6Check your understanding

Quick Quiz

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

Q1. What does substr("Jharkhand", 0, 4) return?
✔ Start at 0, take 4 characters.
Q2. Why use mb_strlen for Hindi text?
✔ Hindi letters use 3 bytes each in UTF-8.
Q3. In a regex, what does ^\d{6}$ match?
✔ ^ and $ anchor the start and end.
🎯
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 2  |  Strings & Regular Expressions
M6Module summary

Recap: Strings & Regular Expressions

What you learned in M6

  • ✔trim, case functions, str_contains/starts_with/ends_with, str_replace, substr.
  • ✔explode splits, implode joins; use mb_* functions for Hindi and emoji.
  • ✔sprintf/printf for templates; number_format and NumberFormatter("en_IN") for money.
  • ✔A regex describes valid text: ^ start, $ end, [ ] choices, \d digit, {n} count.
  • ✔preg_match checks, preg_match_all finds all, preg_replace edits, preg_split splits.
  • ✔Real uses: masking, slugs, validation, parsing messages.
🏆

Module 6 complete!

You practised 10 real examples.

👉 Coming next

M7 Dates, Maths & JSON: ages, due dates, countdowns, OTPs and data exchange with JSON (including PHP 8.3's json_validate).
Complete PHP 8.3 Course  |  Part 2  |  Strings & Regular Expressions
M7

Dates, Maths & JSON

Due dates, ages, fines, OTPs, rounding bills and exchanging data with apps: PHP has strong built-in tools for dates, numbers and JSON.

  • Timestamps and date() formats
  • DateTime, DateTimeImmutable and Asia/Kolkata
  • Adding days, DateInterval and diff()
  • Rounding and maths functions
  • random_int and the Random\Randomizer class
  • json_encode, json_decode and json_validate (PHP 8.3)
YOU WILL BUILD:
Age calculatorFestival countdownLibrary fine calculatorAttendance calendar
📅
Part 2  •  about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M7Where is this used in real work?

Dates and JSON power everyday apps

library.school.in/member.php?id=88
📚 Library card: Nikhil RajPHP
BookDueStatus
Wings of Fire18 Nov 20266 days late: Rs 12 fine
NCERT Physics02 Dec 20267 days left
GET /api/member/88  ->  {"name":"Nikhil Raj","books":2,"fine":14}
⏰

Due dates and reminders

Fee due dates, EMI schedules, library fines, subscription expiry: all date arithmetic.
🎲

Random values

OTPs, coupon codes, lucky draws and temporary passwords need secure random numbers.
🔄

JSON everywhere

Mobile apps, payment gateways and APIs send and receive JSON. PHP reads and writes it in one line.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Concept

Timestamps and date()

  • time(): seconds since 1 Jan 1970 (a Unix timestamp), e.g. 1795000000.
  • date(format, timestamp) turns it into readable text.
  • strtotime('+7 days'), strtotime('2026-12-25') make timestamps from English.
  • mktime(h, i, s, month, day, year) builds one from parts.
LetterGivesLetterGives
d / j05 / 5 (day)D / lWed / Wednesday
m / M / F11 / Nov / NovemberY / y2026 / 26
H / h24h / 12h houri / s / Amin / sec / AM
dates.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Concept

DateTime objects (the modern way)

  • new DateTimeImmutable('2026-11-25', new DateTimeZone('Asia/Kolkata'))
  • ->format('d M Y') same letters as date()
  • ->modify('+1 month') or ->add(new DateInterval('P10D')) (P = period, 10D = 10 days, P1M = 1 month, PT2H = 2 hours)
  • $a->diff($b) gives years, months, days between two dates
Immutable is saferDateTime::modify() changes the original object. DateTimeImmutable returns a new one, so the original date can never change by mistake.
dt.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Animated explainer

How diff() calculates an age

date of birth15 Aug 2008
➤
today25 Nov 2026
200815 Aug 202625 Nov

Whole years: 18

From 15 Aug 2008 to 15 Aug 2026.

Then months: 3

15 Aug → 15 Sep → 15 Oct → 15 Nov.

Then days: 10

15 Nov → 25 Nov.
$dob->diff($today) → y=18, m=3, d=10, days=6676
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Concept

Maths functions and random numbers

FunctionExample
round / floor / ceilround(2.456, 2) = 2.46, floor(9.9)=9, ceil(9.1)=10
abs, max, min, pow, sqrtmax([3, 9, 4]) = 9
fmod, intdiv, %remainders
random_int(a, b)secure random integer (use for OTPs)
new Random\Randomizer()PHP 8.2+: shuffle, pick, and in 8.3 getBytesFromString and getFloat
Do not use rand() for securityrand() and mt_rand() are predictable. OTPs, tokens and passwords must use random_int / random_bytes / Randomizer.
mathrand.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Concept

JSON: talking to apps and APIs

  • JSON is the text format apps use to exchange data: {"name":"Asha","marks":[90,85]}
  • json_encode($array) → JSON text. Flags: JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE (keeps Hindi readable).
  • json_decode($text, true) → associative array (without true you get objects).
  • PHP 8.3: json_validate($text) checks if text is valid JSON without decoding it, faster and uses less memory.
  • JSON_THROW_ON_ERROR makes bad JSON throw an exception you can catch.
json.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 1 of 10  •  Easy

Example 1: Today in Indian format

● Easy💼 Real project: Headers of reports and receipts
Indian documents use day-month-year. One DateTimeImmutable, several formats for different places.
today.php
REAL RUN
✍ Try it yourself Show the financial year, e.g. "FY 2026-27" (April to March).
If month >= 4: FY Y-(Y+1), else (Y-1)-Y. Use (int) $now->format('n').
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 2 of 10  •  Easy

Example 2: Age from date of birth

● Easy💼 Real project: Admission and job forms with age limits
diff() gives the exact age. Forms use it to check eligibility like "18 or older" or "age as on 1 April".
age.php
REAL RUN
✍ Try it yourself Print how many days are left until the next birthday.
Make the birthday in the current year; if it has passed, add 1 year; then ->diff()->days.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 3 of 10  •  Easy

Example 3: Days left to Chhath and exams

● Easy💼 Real project: Countdown banners on websites
Subtract today from a target date. days gives total days; invert is 1 when the date is in the past.
countdown.php
REAL RUN
✍ Try it yourself Sort the events so the nearest upcoming one is first and past events are last.
Use uasort with a comparison on the date strings; or compute days with a sign and sort by it.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 4 of 10  •  Easy

Example 4: Round off a bill

● Easy💼 Real project: Restaurant and pharmacy billing
Bills are rounded to the nearest rupee and the "round off" amount is shown separately, as GST bills do.
roundoff.php
REAL RUN
✍ Try it yourself Some shops always round UP to the next 5 rupees. Write that version.
ceil($gross / 5) * 5
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 5 of 10  •  Easy

Example 5: OTP generator

● Easy💼 Real project: Login and payment OTPs
An OTP must be unpredictable, so we use random_int. str_pad keeps leading zeros (e.g. 004517). It expires after 5 minutes.
otp.php
REAL RUN
✍ Try it yourself Run it 3 times. Do you get the same OTP? Why is that important?
Each run gives a different number. A predictable OTP could be guessed by an attacker.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 6 of 10  •  Medium

Example 6: EMI schedule with dates

● Medium💼 Real project: Loan statements from banks and NBFCs
Each month: interest on the remaining balance, the rest of the EMI reduces the principal. The due date moves by one month each row.
schedule.php
REAL RUN
✍ Try it yourself Add a "Total interest" line at the end.
Keep $totalInt += $int inside the loop.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 7 of 10  •  Medium

Example 7: Library fine calculator

● Medium💼 Real project: School and college library systems
Fine = Rs 2 per day late, but Sundays are not counted and the maximum fine is Rs 100. DatePeriod walks through each day between two dates.
fine.php
REAL RUN
✍ Try it yourself Also skip second Saturdays (holidays in many schools).
Check $day->format('N') === '6' and the day of month between 8 and 14.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 8 of 10  •  Medium

Example 8: Read a JSON config file

● Medium💼 Real project: App settings stored in config.json
Many apps keep settings in a JSON file. JSON_THROW_ON_ERROR stops the app with a clear message if someone breaks the file; ?? supplies defaults for missing keys.
app.phpconfig.json
REAL RUN
✍ Try it yourself Remove the "payment" section from config.json. Does the app crash? Then add a missing comma error and run again.
Missing keys use the ?? default. A syntax error throws JsonException: Syntax error.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 9 of 10  •  Hard

Example 9: Validate and save JSON from an app (json_validate)

● Hard💼 Real project: Receiving orders from a mobile app
A mobile app sends orders as JSON text. We first check it with PHP 8.3's json_validate(), then decode, then check the required fields, then save valid orders to orders.json.
receive.php
REAL RUN
✍ Try it yourself Add a check that total equals the sum of qty x price for each item (add a price field).
Use array_sum(array_map(fn($i) => $i['qty'] * $i['price'], $o['items'])).
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Practice 10 of 10  •  Hard

Example 10: Monthly attendance calendar

● Hard💼 Real project: Attendance and leave dashboards
Builds a real calendar grid for a month: format('N') gives the weekday of the 1st, format('t') the number of days. Present (P), absent (A) and Sundays (-) are marked, then the percentage is calculated.
calendar.php
REAL RUN
✍ Try it yourself Make Saturdays half days that count as 0.5 working days.
When $dow === 6 add 0.5 to $working and 0.5 to $present (if present).
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M7Check your understanding

Quick Quiz

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

Q1. Which format gives "25-11-2026"?
✔ d = day, m = month, Y = 4-digit year.
Q2. Which function should make an OTP?
✔ random_int is cryptographically secure.
Q3. What is new in PHP 8.3 for JSON?
✔ json_validate checks JSON without building arrays.
🎯
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 2  |  Dates, Maths & JSON
M7Module summary

Recap: Dates, Maths & JSON

What you learned in M7

  • ✔Timestamps (time, strtotime) + date() formats for quick work.
  • ✔DateTimeImmutable + DateTimeZone("Asia/Kolkata") for real projects.
  • ✔modify, add(DateInterval), diff() for due dates, ages and countdowns.
  • ✔round/floor/ceil for money; random_int and Randomizer for OTPs and codes.
  • ✔json_encode / json_decode(..., true) to talk to apps and APIs.
  • ✔json_validate() (PHP 8.3) checks JSON before decoding.
🏆

Module 7 complete!

You practised 10 real examples.

👉 Coming next

M8 Files & Directories: save notices, logs, CSV reports and a JSON mini-database to disk.
Complete PHP 8.3 Course  |  Part 2  |  Dates, Maths & JSON
M8

Files & Directories

Programs need to remember things after they finish: logs, reports, uploaded data, backups. PHP can read and write text, CSV and JSON files, and manage folders.

  • file_put_contents and file_get_contents
  • fopen modes, fgets, fwrite, fclose
  • CSV files with fgetcsv and fputcsv
  • A JSON file as a mini database
  • Check, copy, rename and delete files; folders with mkdir, scandir, glob
  • __DIR__, paths and file locking
YOU WILL BUILD:
Visitor logMarks CSV reportJSON student databaseFile organiser
📁
Part 2  •  about 4 hours
10 practice examples: 5 Easy • 3 Medium • 2 Hard
Complete PHP 8.3 Course  |  BrainBit Infotech, Ranchi
M8Where is this used in real work?

Files are a program's long-term memory

📁 school-erp/
  📁 storage/logs/ app-2026-11-25.log (every login and error)
  📁 storage/reports/ fees-nov-2026.csv (opens in Excel)
  📁 storage/backups/ db-2026-11-25.sql
  📁 public/uploads/ photos, admit cards (Module 12)
  📄 config.json settings
  📄 notices.txt notice board text
📝

Logs

Every serious app writes a log file: who logged in, what failed, when. It is the first place you look when something breaks.
📈

CSV reports

Offices live in Excel. PHP exports fee, attendance and sales reports as CSV files that open directly in Excel.
💾

Small data without a database

Settings, caches, small lists and backups are stored as JSON or text files.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Concept

The two easiest functions

  • file_put_contents($file, $text) creates/overwrites a file. Returns bytes written.
  • Add FILE_APPEND to add to the end instead of overwriting.
  • file_get_contents($file) reads the whole file into a string.
  • file($file, FILE_IGNORE_NEW_LINES) reads it as an array of lines.
Look at the Files tabIt shows the real file the program created. Paths are relative to the folder you run php in; __DIR__ means "the folder of this script".
easy.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Animated explainer

fopen modes: how PHP opens a file

r

'r' read

Read only. File must exist. The cursor starts at the beginning.
w

'w' write

Creates the file or empties it first! Cursor at start.
a

'a' append

Creates if missing; always writes at the end. Perfect for logs.
x

'x' exclusive

Create only if it does not exist; fails otherwise. Safe for new files.
$f = fopen('log.txt', 'a')
➤
fwrite($f, "...")
as many times as needed
➤
fclose($f)
Reading line by linewhile (($line = fgets($f)) !== false) { ... } reads one line at a time. A 2 GB log file never fills the memory, unlike file_get_contents. Add + (r+, w+, a+) to both read and write.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Concept

CSV: the language of Excel

  • CSV = comma-separated values. Each line is a row; commas separate columns.
  • fputcsv($f, $array) writes one row (adds quotes when needed).
  • fgetcsv($f) reads one row as an array.
  • Excel opens CSV directly. Add a UTF-8 BOM "\xEF\xBB\xBF" at the start so Excel shows Hindi and the ₹ sign correctly.
PHP 8.3 notePass the escape parameter explicitly, e.g. fgetcsv($f, null, ',', '"', ''). The default escape character is deprecated in PHP 8.4+, so writing it now keeps your code future-proof.
csv.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Concept

Managing files and folders

FunctionDoes
file_exists, is_file, is_dirchecks
filesize, filemtimesize in bytes, last changed time
copy, rename, unlinkcopy, move/rename, delete
mkdir($d, 0777, true)make folders (true = also parents)
scandir, glob('*.csv')list folder contents
pathinfo, basename, dirnameparts of a path

Use / in paths: it works on Windows and Linux. DIRECTORY_SEPARATOR is also available.

manage.php
REAL RUN
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 1 of 10  •  Easy

Example 1: Write a notice file

● Easy💼 Real project: Notice boards and announcements
file_put_contents creates the file in one line. The date is part of the file name so each day gets its own notice.
notice.php
REAL RUN
✍ Try it yourself Write a second notice for 26 Nov with different text. How many files are there now?
Change $date; a new file name is made, so both files remain.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 2 of 10  •  Easy

Example 2: Read the notice

● Easy💼 Real project: Showing saved content on a page
Reading with file() gives an array of lines, so we can number them or print only the first line as a headline.
read.php
REAL RUN
✍ Try it yourself What happens if you read a file that does not exist? Add a check with file_exists first.
PHP gives a warning and returns false. if (!file_exists($f)) { echo "No notice yet"; exit; }
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 3 of 10  •  Easy

Example 3: Visitor log (append)

● Easy💼 Real project: Gate entry registers and audit logs
Each visitor is one line added with FILE_APPEND; LOCK_EX prevents two writes from mixing if two people check in at the same moment.
visitors.php
REAL RUN
✍ Try it yourself Print only the visitors whose purpose contains "Fee".
Loop over $all and use str_contains($line, 'Fee').
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 4 of 10  •  Easy

Example 4: Check if a file exists

● Easy💼 Real project: Installers and first-run setup screens
Apps check whether a config file exists to decide between "first-time setup" and "normal start". is_readable and filesize add more detail.
setup.php
REAL RUN
✍ Try it yourself Run it twice in the same folder. What changes on the second run, and what error appears?
config.json already exists (no "First run"), and mkdir warns that uploads exists. Use if (!is_dir(...)) mkdir(...).
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 5 of 10  •  Easy

Example 5: List files in a folder

● Easy💼 Real project: Download centres and document lists
scandir lists everything (including . and ..); glob filters by pattern. We show name, size in KB and date.
listfiles.php
REAL RUN
✍ Try it yourself Show the total size of all files in the folder in MB.
array_sum(array_map('filesize', glob('downloads/*'))) / 1024 / 1024.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 6 of 10  •  Medium

Example 6: Marks CSV to report

● Medium💼 Real project: Turning an Excel export into a result report
A teacher exports marks from Excel as CSV. PHP reads it, calculates totals and percentages, and writes a new result.csv for printing.
report.phpmarks.csv
REAL RUN
✍ Try it yourself Add a "Rank" column (1 = highest total).
Collect rows in an array first, usort by total, then write them with the position as rank.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 7 of 10  •  Medium

Example 7: JSON student database

● Medium💼 Real project: Small apps that do not need MySQL yet
A JSON file works as a tiny database: load into an array, change it, save it back. Functions load() and save() hide the file details.
studentsdb.php
REAL RUN
✍ Try it yourself Add an update(int $id, string $course) function.
Loop with foreach (load() as &$s) or build a new array with array_map, change the matching id, then save().
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 8 of 10  •  Medium

Example 8: Daily backup with date

● Medium💼 Real project: Automatic backups before updates
Copy important files into a dated backup folder and keep only the last 3 backups, deleting older ones. Real servers run scripts like this every night (cron job / Task Scheduler).
backup.php
REAL RUN
✍ Try it yourself Also add the time (HH-MM) to the folder name so you can back up twice a day.
Use date('Y-m-d_H-i'). The sort still works because the format sorts correctly as text.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 9 of 10  •  Hard

Example 9: File organiser by extension

● Hard💼 Real project: Cleaning a messy Downloads folder
Moves every file into a folder named after its type (Images, Documents, Sheets...). A map from extension to folder makes the rules easy to change; rename moves files.
organise.php
REAL RUN
✍ Try it yourself Add a "dry run" option: print what would move without moving anything.
Wrap rename and mkdir in if (!$dryRun) { ... }.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Practice 10 of 10  •  Hard

Example 10: Sales CSV import with error report

● Hard💼 Real project: Importing data from shops or branches
Real data has mistakes. The importer checks each row (date, quantity, price; 31-02-2026 is caught because PHP would quietly roll it over to 3 March), imports good rows, and writes bad rows with the reason to errors.csv so the office can fix them.
import.phpsales.csv
REAL RUN
✍ Try it yourself Also reject rows where the price is more than Rs 10,000 (probably a typing mistake).
Add an arm (float) $price > 10000 => 'price too high, check' before default.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
M8Check your understanding

Quick Quiz

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

Q1. Which mode wipes a file's old content?
✔ 'w' truncates the file to zero length immediately.
Q2. How do you add a line to the end of a log?
✔ Without FILE_APPEND the file is overwritten.
Q3. Why read a huge file with fgets in a loop?
✔ file_get_contents loads everything into memory at once.
🎯
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 2  |  Files & Directories
M8Module summary

Recap: Files & Directories

What you learned in M8

  • ✔file_put_contents / file_get_contents for quick reads and writes; FILE_APPEND for logs.
  • ✔fopen modes r, w, a, x; fgets and fwrite; always fclose.
  • ✔fputcsv / fgetcsv make Excel-friendly reports.
  • ✔A JSON file can be a tiny database: load, change, save.
  • ✔file_exists, filesize, copy, rename, unlink, mkdir, glob manage files and folders.
  • ✔Validate imported data and report bad rows instead of failing silently.
🏆

Module 8 complete!

You practised 10 real examples.

👉 Coming next

Part 3, M9 PHP Pages & Templates: build real web pages with layouts, includes and query strings.
Complete PHP 8.3 Course  |  Part 2  |  Files & Directories
1 / 1

✎ Code Lab