Sobes.tech
Junior

What data structures do you know in programming?

sobes.tech AI

Answer from AI

  • Arrays (indexed, associative)
  • Stack
  • Queue
  • Linked lists (singly, doubly, cyclic)
  • Trees (binary, balanced, B-tree, etc.)
  • Graphs
  • Hash tables (maps, dictionaries)
  • Sets
  • Heaps

Brief description of some in the context of PHP:

Arrays

PHP arrays are essentially ordered maps, combining properties of arrays and lists. They can contain both numeric and string keys.

<?php
// Indexed array
$indexedArray = [1, 2, 3];

// Associative array
$associativeArray = ['key1' => 'value1', 'key2' => 'value2'];

Stack

Works on the LIFO (Last-In, First-Out) principle. In PHP, it can be implemented using an array and functions array_push(), array_pop().

<?php
$stack = [];
array_push($stack, 'item1'); // Add to the end
array_push($stack, 'item2');
$item = array_pop($stack); // Remove from the end ('item2')

Queue

Works on the FIFO (First-In, First-Out) principle. In PHP, it can be implemented using an array and functions array_push(), array_shift().

<?php
$queue = [];
array_push($queue, 'task1'); // Add to the end
array_push($queue, 'task2');
$task = array_shift($queue); // Remove from the beginning ('task1')

Hash tables / Maps (Associative arrays)

Map keys to values for quick lookup. In PHP, associative arrays are essentially hash tables.

<?php
$map = ['apple' => 'red', 'banana' => 'yellow'];
$color = $map['apple']; // 'red'

Table with examples and descriptions:

Data Structure Working principle Application PHP equivalent/implementation
Array (indexed) Sequential storage Collections of similar data, lists array
Array (associative) Key-value pairs Dictionaries, configurations, form data array
Stack LIFO Operation history, function calls, parsing array with push/pop
Queue FIFO Task processing, buffers array with push/shift
Linked list Elements linked by pointers Dynamic lists, queues, stacks No built-in type, implemented with objects
Tree Hierarchical structure Filesystems, XML/JSON structures, search No built-in type, implemented with objects
Graph Set of vertices and edges Social networks, routing, dependencies No built-in type, implemented with objects
Hash table / Map Fast access by hash of key Caches, dictionaries, associative arrays array (associative)
Set Collection of unique elements Uniqueness check, set operations array with uniqueness check, array_unique
Heap Partially ordered tree Priority queues, heapsort SplHeap, SplPriorityQueue