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
184: Implementing a Hash Table Concept in PHP
You've been using PHP associative arrays since day one of this course. They're great—practically magic. You throw a string key in, you get a value back, and you don't have to worry about how PHP actually finds that value in memory. But if you're going to be a senior engineer, you can't treat the core of your language as a black box. Today, I want to pull back the curtain and actually build a rudimentary hash table from scratch using a basic indexed array.
The search for a faster lookup
Let's imagine we're building a simple cache for a user permission system. I have a few usernames, and I need to store their access levels. If I use a standard indexed array, I have to loop through every single element to find the right user. That's $O(n)$ time complexity, and it's a nightmare once you hit a few thousand users.
$users = [
['name' => 'alice', 'level' => 'admin'],
['name' => 'bob', 'level' => 'editor'],
['name' => 'charlie', 'level' => 'guest'],
];
// To find 'bob', I have to loop. Boring and slow.
I want to be able to jump directly to the index where "bob" is stored without looping. In a perfect world, "bob" would just *be* the index. But arrays don't take strings as indices in a low-level sense; they take integers. So, I need a way to turn the string "bob" into a consistent integer.
Trying a basic hashing function
I'll start by creating a fixed-size array of "buckets." Let's keep it small—say, 10 slots—so we can actually see what's happening. I'll use crc32(), which is a fast way to turn a string into a 32-bit integer, and then use the modulo operator (%) to make sure that number fits within my 10 buckets.
$buckets = array_fill(0, 10, null);
function getIndex($key, $size) {
return abs(crc32($key)) % $size;
}
$user = 'alice';
$index = getIndex($user, 10); // Let's say this returns 4
$buckets[$index] = 'admin';
echo "Alice is at index $index";
This feels like a win. I've mapped a string to a specific integer index. Now I can find Alice instantly. But wait—what happens when I add Bob?
The collision problem
I'm going to add Bob and Charlie to the mix. Here is where the "magic" usually breaks. Because I only have 10 buckets, it's statistically inevitable that two different strings will eventually hash to the same index. This is called a collision.
$usersToStore = [
'alice' => 'admin',
'bob' => 'editor',
'charlie' => 'guest'
];
foreach ($usersToStore as $name => $level) {
$index = getIndex($name, 10);
echo "Storing $name at $index\n";
$buckets[$index] = $level;
}
If I run this and find that both 'alice' and 'charlie' map to index 4, Charlie will simply overwrite Alice. My data is gone. This is the fundamental problem of hash tables. I can't just store the value at the index; I need a way to handle multiple items that claim the same spot.
Solving collisions with chaining
The most common way to fix this is "chaining." Instead of storing the value directly in the bucket, I'll store another array (a "list" or "bucket") at that index. If two users land in the same bucket, they both just live in that smaller list.
Let's rewrite the logic. Now, each bucket starts as an empty array. When I store something, I'll append a key-value pair to that bucket. When I retrieve something, I'll jump to the bucket and then do a very tiny linear search through only the items in that specific bucket.
$buckets = array_fill(0, 10, []);
function store($buckets, $key, $value) {
$index = abs(crc32($key)) % count($buckets);
// We still need to check if the key exists to update it instead of duplicating
foreach ($buckets[$index] as &$pair) {
if ($pair['key'] === $key) {
$pair['value'] = $value;
return $buckets;
}
}
$buckets[$index][] = ['key' => $key, 'value' => $value];
return $buckets;
}
function retrieve($buckets, $key) {
$index = abs(crc32($key)) % count($buckets);
foreach ($buckets[$index] as $pair) {
if ($pair['key'] === $key) {
return $pair['value'];
}
}
return null; // Not found
}
$buckets = store($buckets, 'alice', 'admin');
$buckets = store($buckets, 'bob', 'editor');
$buckets = store($buckets, 'charlie', 'guest');
echo retrieve($buckets, 'bob'); // 'editor'
Now we've actually implemented the core concept of a hash table. We've gone from a slow global search to a fast hash-jump, followed by a very short local search. This is exactly what PHP is doing under the hood when you use $array['key'], just with a much more sophisticated hashing algorithm and a dynamic resizing mechanism so the buckets don't get too crowded.
📋 Practical Task
Exercise: Implementing a Collision-Resistant User Session Store
You are tasked with building a manual session store to better understand hash table collisions. Create a script that does the following:
- Initialize a
$sessionBucketsarray with exactly 5 empty slots. - Create a function called
hashSessionId($id, $size)that usescrc32and the modulo operator to return an index. - Create a function called
setSession($buckets, $sessionId, $data). This function must handle collisions using the "chaining" method (storing an array of pairs within the bucket). - Create a function called
getSession($buckets, $sessionId)that retrieves the data for a specific session ID. - Test your implementation by inserting 10 different session IDs. Given that you only have 5 buckets, collisions will happen. Verify that you can still retrieve the correct data for all 10 sessions without any data being overwritten.
There are no comments for now.