PHP is a versatile server-side scripting language that offers developers an extensive set of collection types to store and manipulate data. This guide will provide a detailed look into PHP’s array lists, linked lists, maps, sets, and other collection types. We’ll explore their unique features and how they can be used in real-life applications.
Array Lists
In PHP, array lists are simply arrays that store values in a sequential manner. They’re a versatile and powerful data structure, allowing developers to store, access, and modify data easily.
Creating an array list:
$arrayList = array(1, 2, 3, 4, 5);
Accessing elements in an array list:
$firstElement = $arrayList[0]; // Returns 1
Adding elements to an array list:
$arrayList[] = 6; // Appends 6 to the end of the array
Linked Lists
Linked lists are a sequential data structure in which elements are stored as nodes with pointers to the next node. They allow for efficient insertion and deletion of elements.
PHP doesn’t have a native linked list implementation. However, you can implement one using the Standard PHP Library (SPL) SplDoublyLinkedList
class:
$linkedlist = new SplDoublyLinkedList();
$linkedlist->push(1);
$linkedlist->push(2);
$linkedlist->push(3);
Maps
Maps, also known as associative arrays or dictionaries, store key-value pairs. They allow for quick lookups, insertions, and deletions based on keys.
Creating a map:
$map = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
Accessing elements in a map:
$value = $map["key1"]; // Returns "value1"
Sets
Sets are a collection of unique elements, without any duplicates. PHP doesn’t have a native set implementation, but you can use the SplObjectStorage
class or an array to mimic set functionality.
Creating a set using an array:
$set = array(1, 2, 3, 4, 5);
$set = array_unique($set); // Ensures uniqueness
Creating a set using SplObjectStorage
:
$set = new SplObjectStorage();
$obj1 = new stdClass();
$obj2 = new stdClass();
$set->attach($obj1);
$set->attach($obj2);
Queues
A queue is a First-In-First-Out (FIFO) data structure, which means that elements are inserted at the end and removed from the front. This collection type is useful in scenarios where you need to maintain the order of elements, such as managing tasks in a multi-threaded environment.
Creating a queue using the SplQueue
class:
$queue = new SplQueue();
$queue->enqueue("Task 1");
$queue->enqueue("Task 2");
$queue->enqueue("Task 3");
Dequeuing elements:
$task = $queue->dequeue(); // Returns "Task 1"
Stacks
A stack is a Last-In-First-Out (LIFO) data structure, meaning that elements are inserted and removed from the top. Stacks are useful in scenarios where you need to reverse the order of elements or manage nested structures like function calls.
Creating a stack using the SplStack
class:
$stack = new SplStack();
$stack->push("Item 1");
$stack->push("Item 2");
$stack->push("Item 3");
Popping elements:
$item = $stack->pop(); // Returns "Item 3"
Heaps
A heap is a priority-based data structure that maintains a partially ordered tree. Elements in a heap are ordered by their priority, which can be determined by custom rules. Heaps are useful when you need to manage elements with different priorities, such as task scheduling or network packet processing.
Creating a min-heap using the SplMinHeap
class:
$minHeap = new SplMinHeap();
$minHeap->insert(3);
$minHeap->insert(1);
$minHeap->insert(2);
Extracting the minimum element:
$minValue = $minHeap->extract(); // Returns 1
Fixed Arrays
Fixed arrays are a collection type with a fixed size, and they provide better performance and memory efficiency compared to standard PHP arrays. They are useful when you know the size of the collection in advance and need to optimize memory usage.
Creating a fixed array:
$fixedArray = new SplFixedArray(3);
$fixedArray[0] = "Item 1";
$fixedArray[1] = "Item 2";
$fixedArray[2] = "Item 3";
Priority Queues
Priority queues are an extension of the queue data structure, where elements are assigned priorities. Elements with higher priorities are dequeued before elements with lower priorities. They are useful in scenarios where you need to manage tasks or resources with varying importance.
Creating a priority queue using the SplPriorityQueue
class:
class MyPriorityQueue extends SplPriorityQueue {
public function compare($priority1, $priority2) {
return $priority2 - $priority1;
}
}
$priorityQueue = new MyPriorityQueue();
$priorityQueue->insert("High Priority", 3);
$priorityQueue->insert("Medium Priority", 2);
$priorityQueue->insert("Low Priority", 1);
Dequeuing elements:
$highestPriority = $priorityQueue->extract(); // Returns "High Priority"
Min-Heap
A Min-Heap is a binary heap data structure where the parent node has a value less than or equal to its children. The root node has the minimum value in the heap. PHP provides the SplMinHeap
class to create and manage min-heaps.
Creating a min-heap:
$minHeap = new SplMinHeap();
$minHeap->insert(5);
$minHeap->insert(3);
$minHeap->insert(1);
Extracting the minimum value:
$minValue = $minHeap->extract(); // Returns 1
Max-Heap
A Max-Heap is a binary heap data structure where the parent node has a value greater than or equal to its children. The root node has the maximum value in the heap. PHP provides the SplMaxHeap
class to create and manage max-heaps.
Creating a max-heap:
$maxHeap = new SplMaxHeap();
$maxHeap->insert(1);
$maxHeap->insert(3);
$maxHeap->insert(5);
Extracting the maximum value:
$maxValue = $maxHeap->extract(); // Returns 5
Custom (Normal) Heap
A Custom Heap, also known as a Normal Heap, allows developers to define their own priority comparison function to determine the order of elements in the heap. PHP provides the SplHeap
class for creating custom heaps. You need to extend the SplHeap
class and implement the compare()
method to specify the custom priority comparison logic.
Creating a custom heap:
class CustomHeap extends SplHeap {
public function compare($value1, $value2) {
// Define your custom comparison logic here.
// Return positive, negative, or 0 based on the comparison.
}
}
$customHeap = new CustomHeap();
$customHeap->insert(1);
$customHeap->insert(3);
$customHeap->insert(5);
Extracting the top-priority value:
$topPriorityValue = $customHeap->extract();
PHP collections offer developers a wide range of data structures to store and manipulate data efficiently. Understanding each collection type’s unique features, use cases, and limitations can help you optimize your applications and make better design decisions.