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
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.
● 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?
✔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
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).
● 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.
● 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 ' : '').
● 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.
● 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') ...
$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.
● 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.
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'])).
● 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).
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
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".
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.
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.
● 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.
● 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.
● 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.