Skip to Content
Course content

60: Big-O Notation with PHP Examples

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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']
Rating
0 0

There are no comments for now.

to be the first to leave a comment.