PHP Data Structures: A Beginner’s Guide to Get Started | 2023

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

PHP Data Structures

This article is a comprehensive overview of data structures along with basic code examples in PHP. The article overview the following six fundamental data structures:

So, let’s begin our journey with the most fundamental and important aspects of computer science and programming – Data structures.

Article Highlights

Following are some important highlights from the article.

  • A data structure is a way of organizing, managing, and storing data in a computer.
  • Different types of data structures differ in terms of storage and retrieval patterns.
  • Choosing the right data structure can greatly improve the efficiency and performance of a program.
  • Data structures can be broadly classified into linear and non-linear classes.
  • An algorithm is a set of well-defined steps or instructions to solve a problem.
  • An array is a linear data structure consisting of a collection of elements. An index or a key identifies each element. 
  • A linked list is a linear data structure that stores data in linked nodes using pointers.
  • A stack is a linear data structure that stores a collection of elements with two main operations: push and pop.
  • A queue is a linear data structure that stores elements in a sequential manner. The elements are added to the back and removed from the front.
  • A tree is a non-linear and hierarchical data structure where each element, called a node, has a parent node and zero or more child nodes.
  • A graph is a non-linear data structure consisting of a set of vertices (nodes) and a set of edges connecting them

Table of Contents

What is a Data Structure?

A data structure is a way of organizing, managing, and storing data in a computer to be accessed and used efficiently. It is a collection of algorithms and methods that are used to represent and manipulate data.

There are many types of data structures, differing on the basis of storage and retrieval patterns and common operations. All of them have their strengths and weaknesses. None is a silver bullet, but the right data structure choice depends on the problem’s nature. 

Choosing the right data structure can greatly improve the efficiency and performance of a program. Following are some common data structures: 

There are other data structures based on these fundamental ones. Each brings a set of features for tackling a wide variety of problems in software programming and development. 

Classification of Data Structures

Data structures can be broadly divided into two categories based on how they store data. The following image shows this division.

php data structures

What is an Algorithm?

The term algorithm usually comes together with data structures, especially in academia. But what is an algorithm?

An algorithm is a set of well-defined steps or instructions designed to solve a specific problem or perform a specific task. It is a finite sequence of instructions that executes in a specific order to solve a problem.

But how is that related to Data structures? So, data structures are ways to organize and store – right. The actions or operations we perform on them are nothing but algorithms. For examples – traversing, adding or deleting elements, and many more.

Data structures and algorithms are intertwined ideas. The choice of both affects how efficiently and effectively an application can perform.

And that’s just the tip of the iceberg. There is much more to say about algorithms, but let’s focus on data structure for now. We will definitely have an article about algorithms in the future.

Array

Introduction

An array is a linear data structure consisting of a collection of elements. An index or a key identifies each element. It is one of the simplest and most widely used data structures in programming. Arrays store and manipulate a fixed-size sequence of elements of the same data type.

php data structures

There are two types of arrays:

  • One-dimensional array: This type of array stores elements in a single row or column.
  • Multi-dimensional array: This type of array arranges elements in a table-like structure consisting of multiple rows and columns.

Arrays are an essential part of programming, and therefore almost every programming language uses them to solve various problems. 

Characteristics

Following are some characteristics of arrays.

  • Homogeneous Data Type: An array can hold a fixed number of elements, which all have the same data type.
  • Contiguous Memory Allocation: An array stores elements in contiguous memory locations, meaning that they occupy adjacent memory blocks. This allows for efficient access to array elements using indexing.
  • Fixed Size: The size of an array is fixed at the time of creation and cannot be changed during runtime.
  • Random Access: Since an array stores elements in contiguous memory locations, accessing any element of an array takes the same amount of time regardless of the element’s position in the array. This allows for random access to array elements using their index.
  • Static: Arrays are considered static data structures because their size is fixed at the time of creation. It cannot be dynamically resized during runtime.
  • Efficient for Searching and Sorting: Arrays are very efficient for searching and sorting operations because of their fixed size and random access property.

Common functions

Following are some common functions of arrays.

  • Accessing elements: accessing an element by its index or key.
  • Insertion: inserting an element at a specific index or at the end of the array.
  • Deletion: deleting an element at a specific index or based on its value.
  • Sorting: sorting the elements in ascending or descending order.
  • Searching: searching for a specific element and returning its index or boolean value indicating whether it is present in the array.

Applications

Following are some applications of arrays.

  • Storing and accessing data: Stores and retrieves data quickly and efficiently. They provide a way to organize data in a linear fashion and allow for fast access to individual elements by index.
  • Sorting and searching: Sorting algorithms, such as merge sort or quicksort, rely heavily on arrays to manipulate and organize data.
  • Implementing dynamic data structures: Implements underlying data structure for more complex data structures, such as stacks, queues, and hash tables. 
  • Image processing: In image processing applications. Each pixel of an image is as an element in a multidimensional array.
  • Numerical analysis: In numerical analysis applications, such as scientific computing and simulation. Arrays provide an efficient way to store and manipulate large data sets, such as matrices and vectors.
  • Graphical user interfaces (GUIs): In graphical user interface (GUI) programming. They store and manage the layout and appearance of interface components.
  • Game development: Arrays are essential to game development. They store and manipulate game data, such as player scores, character attributes, and game maps.
  • Data analysis: In data analysis applications to store and manipulate large sets of data, such as spreadsheets or databases. They can perform calculations and generate statistical analyses quickly.

Use cases

Following are some real life use cases of arrays.

  • Storing and accessing information in databases: In database management systems to store and retrieve data. Each column in a database table acts as an array, making managing large amounts of data easier.
  • Image processing: Image data is a two-dimensional array of pixels, where each pixel contains information about color and brightness. This makes it easier to process images using various algorithms.
  • Signal processing: Represent signals in fields such as audio processing and telecommunications. This allows for easy analysis and manipulation of signals using various techniques.
  • Statistical analysis: In statistics to store and manipulate large amounts of data. This allows for the calculation of various statistical measures, such as mean, median, and standard deviation.
  • Game development: Arrays can store game objects and their properties, such as position, velocity, and orientation. This allows for easy manipulation of game objects during gameplay.
  • Mathematical computations: In mathematics to represent vectors and matrices. This allows for easy manipulation of mathematical objects using various algorithms and techniques.

Code Example

Following is a basic code example of an array PHP data structure.

<?php


$array = [1, 2, 3];


array_push($array, 4); //  [1, 2, 3, 4]


array_pop($array); // 4


$array = array_merge($array, [4, 5]); // [0, 1, 2, 3, 4, 5]


foreach($array as $element) echo $element. " "; // 1 2 3 4 5


?>

Linked List

Introduction

A linked list is a linear data structure that stores data in linked nodes using pointers instead of contiguous blocks of memory.

Think of a linked list as a chain. Each node in a chain links to another in a sequential fashion.

The linked list has different variants depending on how nodes link together. The following are variants of a linked list.

  • Singly-linked list.
  • Doubly-linked list.
  • Circular linked list.
  • Doublyc circular linked list.
linkedlist

Characteristics

Following are some characteristics of linked lists.

  • Linear: A linked list is a linear data structure, meaning that its elements are arranged in a sequence or order.
  • Dynamic: Unlike arrays, linked lists can dynamically grow and shrink in size, allowing for efficient insertion and deletion of elements.
  • Non-contiguous: The elements in a linked list are not stored contiguously in memory, but rather each element is stored in a separate node with reference to the next (and sometimes previous) element.
  • Head and tail: Linked lists usually have a head and tail node, which are the first and last nodes in the list, respectively.
  • Pointers: Linked lists rely on pointers to connect the nodes, which uses some extra memory but allows dynamic allocation and efficient deletion of nodes.
  • Traversal: To access the elements in a linked list, you must traverse the list starting from the head node, following the pointers to each subsequent node until you find the desired element.
  • Singly or doubly linked: Linked lists can be singly linked, meaning that each node only has a reference to the next node, or doubly linked, meaning that each node has a reference to both the next and previous nodes.
  • Circular: A linked list can be circular if the last node points back to the first node, creating a loop.
  • Memory efficiency: Linked lists are memory-efficient for certain operations like insertion and deletion. However, accessing a specific element can be slower than in an array due to the need to traverse the list linearly.

Common functions

Following are some common functions of linked lists.

  • Insertion: Inserting a new node into a linked list involves creating a new node and updating the pointers of the adjacent nodes to connect the new node.
  • Deletion: Removing a node from a linked list involves updating the pointers of the adjacent nodes to bypass the node being removed and freeing the memory occupied by the removed node.
  • Traversal: To access each element in a linked list, you have to traverse the list starting from the head node, following the pointers to each subsequent node until you reach the end of the list.
  • Searching: To find a specific element in a linked list, you have to traverse the list and compare the data of each node with the desired element.
  • Reversal: Reversing a linked list involves reversing the pointers of each node to point to the previous node instead of the next node.

Applications

Following are some applications of linked lists.

  • Stacks and Queues: Implements the stack and queue data structures.
  • Hash Tables: Implements the separate chaining technique for resolving collisions in hash tables.
  • Graphs: Represents graphs, where each node in the linked list represents a vertex, and the pointers represent edges connecting the vertices.
  • File Systems: Many file systems use linked lists to manage the allocation and deallocation of disk space.
  • Dynamic Memory Allocation: Each node represents a block of memory and the pointers represent the free space between the blocks.
  • Garbage Collection: Some garbage collection algorithms use linked lists to keep track of memory which is no longer useful.

Use cases

Following are some real life use cases of linked lists

  • Web Browsers: Web browsers often use a linked list to implement their browsing history. Each visited webpage is represented by a node in the linked list, with pointers to the previous and next pages visited.
  • Music Players: Music players can use a linked list to implement their playlist functionality. Each song is represented by a node in the linked list, with pointers to the previous and next songs in the playlist.
  • Video Players: Similarly, video players can use a linked list to implement their playlist functionality. Each video is represented by a node in the linked list, with pointers to the previous and next videos in the playlist.
  • Operating Systems: Operating systems use linked lists to manage their process scheduling queues. Each process waiting to be executed is represented by a node in the linked list, with pointers to the previous and next processes in the queue..
  • Image Processing: In image processing, linked lists can be used to implement linked component analysis (LCA), a technique for identifying and grouping connected pixels in an image.
  • Symbol Tables: In compilers and interpreters can use them to implement symbol tables, which are used to store information about variables, functions, and other program elements.
  • Navigation Systems: Navigation systems can use linked lists to represent routes and directions. Each location on the route is represented by a node in the linked list, with pointers to the previous and next locations.

Code Example

Following is a basic code example of a linked list PHP data structure.

<?php


class Node {
  public $data;
  public $next;


  public function __construct($data) {
    $this->data = $data;
    $this->next = null;
  }
}


class LinkedList {
  public $head;


  public function __construct() {
    $this->head = null;
  }


  public function insert($data) {
    $newNode = new Node($data);


    if ($this->head === null) {
      $this->head = $newNode;
    } else {
      $current = $this->head;
      while ($current->next !== null) {
        $current = $current->next;
      }
      $current->next = $newNode;
    }
  }


  public function delete($data) {
    if ($this->head === null) {
      return;
    }


    if ($this->head->data === $data) {
      $this->head = $this->head->next;
      return;
    }


    $current = $this->head;
    while ($current->next !== null) {
      if ($current->next->data === $data) {
        $current->next = $current->next->next;
        return;
      }
      $current = $current->next;
    }
  }


  public function display() {
    if ($this->head === null) {
      echo "Empty list";
    } else {
      $current = $this->head;
      while ($current !== null) {
        echo $current->data . " ";
        $current = $current->next;
      }
    }
  }
}


$list = new LinkedList();
$list->insert(5);
$list->insert(10);
$list->insert(15);
$list->display(); // Output: 5 10 15
$list->delete(10);
$list->display(); // Output: 5 15


?>

Stack

Introduction

A stack is a linear data structure that stores a collection of elements with two main operations: push and pop. It is similar to a stack of plates, where the last plate added is the first one to be removed (LIFO – Last-In-First-Out). Elements are added and removed from only one end, called the top of the stack. 

php data structures

Characteristics

Following are some characteristics of stacks

  • Linear: A stack is a linear data structure that stores a collection of elements with two main operations: push and pop.
  • FIFO: It follows the Last-In-First-Out (LIFO) principle, which means that the added last element is the first to be removed.
  • One End: Elements can only be added or removed from the top of the stack.
  • Implementation: A stack can be implemented using an array or a linked list data structure.
  • Stackoverflow: A stack has a limited size, and if the stack becomes full and an element is pushed onto it, it causes a stack overflow, which can lead to program termination or other errors 

Common functions

Following are some common functions of stacks.

  • Push: Adds an element to the top of the stack.
  • Pop: Removes the element at the top of the stack and returns it.
  • Peek/Top: Returns the element at the top of the stack without removing it.
  • Size: Returns the number of elements in the stack.
  • isEmpty: Checks if the stack is empty.
  • isFull: Checks if the stack is full (for stack implementations with a fixed size).
  • Clear: Removes all the elements from the stack.

Applications

Following are some applications of stacks.

  • Expression evaluation and syntax parsing: Evaluates mathematical expressions and to parse the syntax of programming languages and compilers.
  • Backtracking algorithms: Backtracking algorithms such as maze solving, graph traversal, and depth-first search to keep track of the path taken and to backtrack when necessary.
  • Function call management: Keeps track of function calls and local variables in computer memory.
  • Undo and redo functionality: Implements undo and redo functionality in software applications by storing the state of the application at each step.
  • Web browsing: Stores the history of visited web pages, enabling the back and forward buttons in web browsers.
  • Simulation of real-world stacks: Simulates real-world stacks, such as a pile of plates or a deck of cards.

Use cases

Following are some real life use cases of stacks.

  • Web browsing: Stores the history of visited web pages, enabling the back and forward buttons in web browsers.
  • Text editors: Implements undo and redo functionality in text editors, allowing users to reverse and repeat the last performed action.
  • Function call management: Computer memory uses keep track of function calls and local variables, making it easier to manage and organize program execution.
  • Memory management: Computer memory uses a stack to manage the allocation and deallocation of memory in programming languages. When a function is called, the stack is used to allocate memory for the function’s local variables and when the function returns, the stack is used to deallocate the memory.
  • Recursive algorithms: In programming, recursive algorithms such as depth-first search, quicksort and towers of Hanoi use a stack to keep track of the recursive calls and their corresponding data.

Code Example

Following is a basic code example of a stack PHP data structure.

<?php


class Stack {
    private $items = array();


    public function push($item) {
        array_push($this->items, $item);
    }


    public function pop() {
        return array_pop($this->items);
    }


    public function peek() {
        return end($this->items);
    }


    public function isEmpty() {
        return empty($this->items);
    }


    public function size() {
        return count($this->items);
    }
}


$stack = new Stack();
$stack->push(1); // 1
$stack->push(2); // 1 2
$stack->push(3); // 1 2 3
$stack->size(); // 3
$stack->pop(); // 1 2
$stack->peek() // 2

?>

Queue

Introduction

A queue is a linear data structure that stores elements in a sequential manner. The elements are added to the back and removed from the front, following the “first-in, first-out” (FIFO) principle. Think of a queue as a line of people waiting for something, where the person who arrives first is the first to be served and the person who arrives last is the last to be served. 

queue

Characteristics

Following are some characteristics of queues.

  • FIFO: Elements are added to the back and removed from the front of the queue, following the “first-in, first-out” (FIFO) principle.
  • Implementation: Queues can be implemented using arrays or linked lists, with arrays being more efficient for small queues and linked lists being more efficient for larger queues.
  • Double-ended: Queues have a front and a rear end, with new elements being added to the rear and removed from the front.
  • Storage: Queues can be empty, where no elements are present, or full, where no more elements can be added. In some implementations, new elements overwrite the oldest elements when the queue is full.
  • Enqueue & Dequeue: Queue operations include enqueue (adding an element to the rear), dequeue (removing an element from the front), peek (returning the front element without removing it), and checking if the queue is empty or full.

Common functions

Following are some common functions of queues.

  • Enqueue: Adds an element to the back (rear) of the queue.
  • Dequeue: Removes and returns the element at the front of the queue.
  • Peek: Returns the element at the front of the queue without removing it.
  • IsEmpty: Checks if the queue is empty.
  • IsFull: Checks if the queue is full (in cases with a fixed size).
  • Size: Returns the number of elements in the queue.

Applications

Following are some applications of queues.

  • Process scheduling: Operating systems commonly use queues to manage process scheduling. Processes are added to a queue and executed in the order they were added, following the “first-in, first-out” principle.
  • Printer queues: Print jobs are added to a printer queue and processed in the order they were added, with the first job in the queue being printed first.
  • Message queues: Distributed computing systems use message queues to transfer messages between processes or systems. Messages are added to the queue and processed in the order they were added.
  • Web server request handling: When a web server receives multiple requests simultaneously, it places them in a queue and processes them one at a time, following the “first-in, first-out” principle.
  • BFS in graph algorithms: Breadth-first search (BFS) algorithms use a queue to traverse a graph or tree. Nodes are added to the queue in the order they are discovered and processed in the order they were added.

Use cases

Following are some real-life use cases of queues.

  • Job scheduling: Computer systems often use queues to manage jobs that are waiting to be processed by a CPU or a network server. Jobs are added to the queue as they arrive and are processed in the order in which they were added.
  • Data buffering: Buffers data between different pipelines or processing system stages. This can help smooth out data flow variations and improve overall system performance.
  • Printing: Printers use queues to manage the print jobs that are waiting to be printed. Jobs are added to the queue as they are submitted by users and are printed in the order in which they were received.
  • Event Loop: Event-driven programming uses queues to manage events that occur asynchronously. In this context, events are added to a queue as they occur, and a separate process, often called an event loop, processes them in the order in which they were received.

Code Example

Following is a basic code example of a queue PHP data structure.

<?php


class Queue {
    private $items;
 
    public function __construct() {
      $this->items = array();
    }
 
    public function enqueue($item) {
      array_push($this->items, $item);
    }
 
    public function dequeue() {
      if ($this->isEmpty()) {
        return null;
      } else {
        return array_shift($this->items);
      }
    }
 
    public function peek() {
      return $this->isEmpty() ? null : $this->items[0];
    }
 
    public function isEmpty() {
      return empty($this->items);
    }
 
    public function size() {
      return count($this->items);
    }
  }
 
  // Example usage:
  $q = new Queue();
  $q->enqueue("apple");
  $q->enqueue("banana");
  $q->enqueue("orange");
 
  echo $q->dequeue() . "\n";  // Output: apple
  echo $q->peek() . "\n";     // Output: banana
  echo $q->dequeue() . "\n";  // Output: banana
  echo $q->isEmpty() . "\n";  // Output: false
  echo $q->size() . "\n";     // Output: 1
 
?>

Tree

Introduction

A tree is a non-linear and hierarchical data structure where each element, called a node, has a parent node and zero or more child nodes. The topmost node in the tree is called the root node, while nodes without children are called leaf nodes. Trees are used to represent relationships among elements, such as family trees or file system directories.

php data structures

There are several types of trees, including:

  • Binary Tree: A binary tree is a tree in which each node has at most two children, referred to as the left child and the right child.
  • Binary Search Tree: A binary search tree is a binary tree in which the left child of a node has a value less than or equal to the parent node, and the right child has a value greater than or equal to the parent node. This property makes it efficient for searching and sorting.
  • AVL Tree: An AVL tree is a self-balancing binary search tree in which the heights of the two child subtrees of any node differ by at most one. This ensures that the tree is balanced and the operations on the tree are efficient.
  • B-Tree: A B-tree is a self-balancing search tree in which each node can have more than two children. It is commonly used in databases and file systems to store large amounts of data.
  • Trie: A trie is a tree-like data structure that stores and searches associative arrays, where the keys are usually strings. The nodes in the trie represent the characters in the key.

Characteristics

Following are some characteristics of trees.

  • Hierarchical: A tree is a hierarchical data structure that is used to represent a collection of nodes.
  • Composition: A tree is composed of nodes and edges. Each node in a tree has a parent node and zero or more child nodes.
  • Edge: An edge is a link or connection between two nodes. 
  • Root Node: The topmost node in a tree is called the root node.
  • Leaf Node: Nodes with no children are called leaf nodes.
  • Depth: The depth of a node is the number of edges from the root node to the node.
  • Height: The height of a tree is the maximum depth of any node in the tree.

Common functions

Following are some common functions of trees.

  • Insertion: Adding a new node to the tree.
  • Deletion: Removing a node from the tree.
  • Traversal: Visiting all the nodes in the tree in a particular order.
  • Searching: Finding a specific node in the tree.
  • Height: Finding the height of the tree (the maximum number of edges from the root to a leaf).
  • Depth: Finding the depth of a node (the number of edges from the root to the node).
  • Balancing: Ensuring that the tree remains balanced to optimize performance for certain operations.

Applications

Following are some applications of trees.

  • File systems: Represents file systems on computers, with directories represented as nodes and files represented as leaves.
  • Organization charts: Represents the hierarchical structure of organizations, where nodes represent employees and branches represent their managers.
  • Search algorithms: Search algorithms often use trees such as binary search trees and AVL trees to efficiently search for and retrieve data.
  • Game trees: Represent the possible moves and outcomes of games such as chess or tic-tac-toe, allowing players or AI to make decisions based on predicted outcomes.

Use cases

Following are some real life uses case of trees.

  • Parsing and evaluating mathematical expressions: Represent mathematical expressions in a way that can be easily parsed and evaluated. Each node in the tree represents an operator or operand in the expression, and the branches represent the order of operations.
  • Decision-making processes: Decision trees are a common tool in machine learning and data science for making decisions based on a set of criteria. Each node in the tree represents a decision point, with branches representing the possible outcomes of that decision.
  • HTML and XML parsing: HTML and XML documents can be parsed and represented as a tree structure, with each node representing a tag or element in the document.
  • Network routing: Network routing algorithms often use trees to represent the routing paths between nodes in a network.
  • Huffman coding: Data compression algorithms like Huffman coding, where each node represents a character or symbol, and the branches represent the encoding of that symbol.
  • Computer file systems: File systems like NTFS, HFS+, and ext3 use tree structures to organize and manage files and directories.
  • Database indexing: Database indexing uses B-trees and other types to efficiently search for and retrieve data.

Code Example

Following is a basic code example of a tree PHP data structure.

<?php


class Node {
    public $data;
    public $left;
    public $right;
   
    public function __construct($data) {
        $this->data = $data;
        $this->left = null;
        $this->right = null;
    }
}


class BinaryTree {
    private $root;
   
    public function __construct() {
        $this->root = null;
    }
   
    public function insert($data) {
        $newNode = new Node($data);
        if ($this->root == null) {
            $this->root = $newNode;
        } else {
            $current = $this->root;
            while (true) {
                if ($data < $current->data) {
                    if ($current->left == null) {
                        $current->left = $newNode;
                        break;
                    }
                    $current = $current->left;
                } else {
                    if ($current->right == null) {
                        $current->right = $newNode;
                        break;
                    }
                    $current = $current->right;
                }
            }
        }
    }
   
    public function traverseInorder($node) {
        if ($node != null) {
            $this->traverseInorder($node->left);
            echo $node->data . " ";
            $this->traverseInorder($node->right);
        }
    }
   
    public function printInorder() {
        $this->traverseInorder($this->root);
    }
}


$tree = new BinaryTree();
$tree->insert(5);
$tree->insert(3);
$tree->insert(7);
$tree->insert(1);
$tree->insert(9);
$tree->insert(4);


echo "Inorder traversal: ";
$tree->printInorder(); // Output: 1 3 4 5 7 9


?>

Graph

Introduction

A graph is a non-linear data structure consisting of a set of vertices (nodes) and a set of edges connecting them. Each vertex represents an entity, while each edge represents a connection or a relationship between the entities. 

graph

Graphs can be directed or undirected, weighted or unweighted, cyclic or acyclic, and they can be represented using various data structures, such as adjacency matrix, adjacency list, or edge list.

Characteristics

Following are some characteristics of graphs.

  • Vertices (nodes): A graph is made up of a set of vertices, which represent points or objects. In a directed graph, there are arrows that connect the vertices, indicating the direction of the relationship between them.
  • Edges: The connections between vertices are called edges. Edges can be directed or undirected, weighted or unweighted.
  • Paths: A path is a sequence of edges that allows you to move from one vertex to another in the graph.
  • Cycles: A cycle is a path that starts and ends at the same vertex.
  • Degree: The degree of a vertex is the number of edges that are incident to that vertex. In a directed graph, the degree is separated into in-degree and out-degree.
  • Connectedness: A graph is connected if there is a path between any two vertices in the graph.
  • Weighted: Some edges can have associated weights or costs, representing some kind of distance or cost to travel along that edge.
  • Directed: In a directed graph, the edges have a direction, meaning they point from one vertex to another in a specific way.
  • Acyclic: A graph is acyclic if it does not contain any cycles.

Common functions

Following are some common functions of graphs.

  • Add Vertex: Adding a vertex to a graph involves creating a new node with the given value and adding it to the list of vertices.
  • Add Edge: Adding an edge between two vertices involves creating a new edge with the given weight and connecting the two vertices.
  • Remove Vertex: Removing a vertex from a graph involves removing the node from the list of vertices and removing any edges that are connected to it.
  • Remove Edge: Removing an edge between two vertices involves removing the edge from the list of edges and updating the adjacency list of the two vertices.
  • Traverse: Traversing a graph involves visiting all vertices and edges in the graph in a particular order. Common traversal algorithms include depth-first search and breadth-first search.
  • Find Path: Finding a path between two vertices involves searching the graph for a sequence of edges that connect the two vertices.
  • Find Shortest Path: Finding the shortest path between two vertices involves searching the graph for the path with the lowest total weight. Common algorithms for finding the shortest path include Dijkstra’s and Bellman-Ford’s algorithms.
  • Find Connected Components: Finding the connected components of a graph involves identifying groups of connected vertices. This can be useful for clustering or analyzing network structures.
  • Find Cycles: Finding cycles in a graph involves identifying sequences of edges that loop back to a vertex. This can be useful for detecting patterns or identifying potential problem areas in a network.

Applications

Following are some applications of graphs.

  • Social networks: Models social networks, with people as nodes and relationships between them as edges. This allows for analysis of the structure of the network and the relationships between individuals.
  • Transportation networks: Models transportation networks such as roads, railways, and air routes. This allows for finding the shortest path between two locations, determining the optimal route for transportation, and optimizing traffic flow.
  • Internet and Web: Models the Internet and the World Wide Web, with web pages as nodes and links between them as edges.
  • Computer networks: Models computer networks, with computers as nodes and connections between them as edges. This allows for the optimization of network routing and flow control.

Use cases

Following are some real life use cases of graphs.

  • Social networks: Models social networks like Facebook, LinkedIn, and Twitter. A node represents each user in the network, and edges connect nodes that are friends or have some type of relationship.
  • Route planning: Models transportation networks like roads, highways, and air routes. A node represents each intersection or airport, and edges represent the roads or flights between them. 
  • Internet search: Models the web pages on the internet and the links between them. Graph algorithms can be used to rank pages based on their importance and relevance to a search query and to identify spam or malicious websites.
  • Image segmentation: Models images and identify objects within them. Each pixel in the image is represented by a node, and edges connect adjacent pixels.
  • Circuit design: Models electronic circuits and analyze their behavior. A node represents each component in the circuit, and edges represent the connections between components.

Code Example

Following is a basic code example of a graph PHP data structure.

<?php




class Graph {
    private $adjacency_list = [];


    // Add a new node to the graph
    public function addNode($node) {
        $this->adjacency_list[$node] = [];
    }


    // Add a new edge between two nodes in the graph
    public function addEdge($node1, $node2) {
        array_push($this->adjacency_list[$node1], $node2);
        array_push($this->adjacency_list[$node2], $node1);
    }


    // Traverse the graph using Depth First Search algorithm
    public function DFS($start_node) {
        $visited = [];
        $stack = [];


        array_push($stack, $start_node);


        while (!empty($stack)) {
            $current_node = array_pop($stack);
            if (!in_array($current_node, $visited)) {
                array_push($visited, $current_node);
                foreach ($this->adjacency_list[$current_node] as $neighbor) {
                    array_push($stack, $neighbor);
                }
            }
        }


        return $visited;
    }


    // Traverse the graph using Breadth First Search algorithm
    public function BFS($start_node) {
        $visited = [];
        $queue = [];


        array_push($queue, $start_node);


        while (!empty($queue)) {
            $current_node = array_shift($queue);
            if (!in_array($current_node, $visited)) {
                array_push($visited, $current_node);
                foreach ($this->adjacency_list[$current_node] as $neighbor) {
                    array_push($queue, $neighbor);
                }
            }
        }


        return $visited;
    }
}


// Example usage
$graph = new Graph();
$graph->addNode("A");
$graph->addNode("B");
$graph->addNode("C");
$graph->addNode("D");
$graph->addEdge("A", "B");
$graph->addEdge("B", "C");
$graph->addEdge("C", "D");
$graph->addEdge("D", "A");


echo "DFS traversal: " . implode(", ", $graph->DFS("A")) . "\n"; //DFS traversal: A, D, C, B
echo "BFS traversal: " . implode(", ", $graph->BFS("A")) . "\n"; //BFS traversal: A, B, D, C




?>

Using Data Structures in PHP

In conclusion, data structures and algorithms are essential concepts for any programmer or developer. They are the building blocks for solving complex problems and optimizing code. There are different data structures, such as arrays, linked lists, stacks, queues, trees, and graphs. They enable developers to choose the most appropriate structure for a given problem. 

Therefore, implementing these structures in PHP or any other programming language can greatly enhance the performance of an application. It is important to clearly understand the characteristics, operations, and use cases of each data structure to maximize their potential. 

So combining data structures and algorithms effectively, developers can create efficient and optimized solutions.

So, we hope you have enjoyed this article. Stay tuned for more at FuelingPHP.

PHP Fundamentals Article Series

This article is part of our series on learning the fundamentals of PHP web development. If you are stepping into your PHP journey. Check out the articles in this series to get deeper into PHP.