PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
60: Big-O Notation with PHP Examples
Why should I even care about Big-O notation in PHP?
I get it. When you're working with a small dataset—say, a few dozen rows from a database—your code feels instant regardless of how you write it. But Big-O isn't about how fast your code runs today; it's about how it behaves as your data grows. It's a way of describing the "scalability" of your algorithm.
Think of it this way: if you write a function that takes 1 millisecond to process 10 items, but 1 second to process 1,000 items, and 10 minutes to process 10,000 items, you've got a scaling problem. In a production environment, that's how you crash a server. Big-O gives us a common language to say, "This approach is linear" (O(n)) or "This approach is quadratic" (O(n²)), so we can spot the bottlenecks before they hit production.
How do I actually spot O(n) vs O(n²) in my PHP loops?
The easiest way to visualize this is by looking at your loops. If you have one loop iterating through an array of users to find a specific one, that's O(n). If the array doubles in size, the time it takes to finish roughly doubles. That's linear growth.
// O(n) - Linear Time
function findUserByEmail($users, $email) {
foreach ($users as $user) {
if ($user['email'] === $email) {
return $user;
}
}
return null;
}
Now, the danger zone is the nested loop. If you're looping through a list and, inside that loop, you loop through that same list again, you've hit O(n²). If you have 1,000 users, you're now performing 1,000,000 checks. This is where PHP scripts start hitting the max_execution_time limit.
// O(n^2) - Quadratic Time
function findDuplicateEmails($users) {
$duplicates = [];
foreach ($users as $userA) {
foreach ($users as $userB) {
if ($userA !== $userB && $userA['email'] === $userB['email']) {
$duplicates[] = $userA['email'];
}
}
}
return array_unique($duplicates);
}
I've seen developers write code like the second example for small projects, only to have the site grind to a halt once they hit a few thousand customers. Avoid nested loops over the same dataset whenever possible.
Is using an associative array always O(1)?
For the most part, yes. When we talk about O(1), or "Constant Time," we mean the operation takes the same amount of time regardless of whether the array has 10 elements or 10 million. Accessing a value by its key in a PHP associative array is a hash table lookup, which is incredibly efficient.
Compare these two ways of checking if a product ID exists in a list:
// O(n) - We have to scan the whole list potentially
$productIds = [101, 102, 103, 104];
if (in_array(104, $productIds)) {
// slow as the list grows
}
// O(1) - Direct jump to the memory address
$productIds = [
101 => true,
102 => true,
103 => true,
104 => true
];
if (isset($productIds[104])) {
// instant, regardless of list size
}
This is a pro tip: if you find yourself calling in_array() inside a loop, you are accidentally creating an O(n²) algorithm. Flip your array so the values are keys, and you've just optimized your code back down to O(n).
Can I actually turn an O(n²) problem into an O(n) one?
Absolutely, and this is where the magic happens. Let's go back to that duplicate email example. Instead of comparing every user to every other user, we can use a temporary "lookup table" (an associative array) to remember who we've already seen.
// O(n) - Linear Time
function findDuplicateEmailsOptimized($users) {
$seen = [];
$duplicates = [];
foreach ($users as $user) {
$email = $user['email'];
if (isset($seen[$email])) {
$duplicates[] = $email;
}
$seen[$email] = true;
}
return $duplicates;
}
Notice what happened here? We only loop through the users once. We use a little bit more memory (the $seen array) to gain a massive amount of speed. In the software world, we call this a "time-space tradeoff." I'll take extra RAM over a timed-out server any day.
📋 Practical Task
Optimizing the Order Collision Detector
You have been handed a legacy function that checks if any two orders in a batch have the same transaction_id. The current implementation uses nested loops, and it's causing the payment gateway to time out when batches exceed 500 orders.
Your Task: Rewrite the detectCollisions function. You must replace the nested loop approach with a more efficient O(n) approach using an associative array as a lookup table. Ensure the function still returns an array of the colliding transaction IDs.
function detectCollisions(array $orders): array {
$collisions = [];
// CURRENT SLOW IMPLEMENTATION:
// foreach ($orders as $orderA) {
// foreach ($orders as $orderB) {
// if ($orderA !== $orderB && $orderA['tx_id'] === $orderB['tx_id']) {
// $collisions[] = $orderA['tx_id'];
// }
// }
// }
// YOUR OPTIMIZED CODE HERE
}
// Test Data
$batch = [
['id' => 1, 'tx_id' => 'ABC-123'],
['id' => 2, 'tx_id' => 'XYZ-789'],
['id' => 3, 'tx_id' => 'ABC-123'], // Collision!
['id' => 4, 'tx_id' => 'LMN-456'],
['id' => 5, 'tx_id' => 'XYZ-789'], // Collision!
];
print_r(detectCollisions($batch));
// Expected Output: ['ABC-123', 'XYZ-789']
There are no comments for now.