Discovering PHP Data Structures: Arrays, Linked Lists, and Binary Trees

London Lingo
9 min readMay 25, 2023

--

Data structures are one of the most fundamental concepts in computer science and programming. They are the ways of organizing and storing data in memory so that they can be accessed and manipulated efficiently. Different data structures have different properties and trade-offs, such as speed, memory usage, and complexity.

In this post, we will explore three common data structures that are widely used in programming: arrays, linked lists, and binary trees. We will learn what they are, how they work, and how to use them in PHP. By the end of this post, you will have a better understanding of these data structures and be able to choose the right one for your needs.

Arrays

An array is a data structure that stores a collection of values of the same type in a contiguous block of memory. Each value in an array has a unique index that indicates its position in the array. The index starts from zero and goes up to the length of the array minus one.

In PHP, there are two ways to create and access arrays: using the array() function or the square bracket syntax. For example, we can create an array of five numbers using either of these methods:

// Using the array() function
$numbers = array(1, 2, 3, 4, 5);

// Using the square bracket syntax
$numbers = [1, 2, 3, 4, 5];

To access an element in an array, we can use the square bracket syntax with the index of the element. For example, to get the third element in the $numbers array, we can write:

// Get the third element
$third = $numbers[2]; // Note that the index starts from zero

To modify an element in an array, we can assign a new value to it using the same syntax. For example, to change the fourth element in the $numbers array to 10, we can write:

// Change the fourth element
$numbers[3] = 10;

Arrays have some advantages and disadvantages as a data structure. Some of the advantages are:

  • Arrays are simple and easy to use
  • Arrays allow random access to any element in constant time
  • Arrays are efficient in terms of memory usage

Some of the disadvantages are:

  • Arrays have a fixed size and cannot be resized dynamically
  • Arrays can be wasteful if there are many empty slots or unused elements
  • Arrays can be slow to insert or delete elements as it requires shifting other elements

Arrays are suitable for situations where we need to store a fixed number of elements that are accessed frequently and randomly. Some examples of common use cases for arrays are:

  • Storing a list of options or choices
  • Storing a sequence of characters or bytes
  • Storing a matrix or a grid of values

Linked Lists

A linked list is a data structure that stores a collection of values of any type in a series of nodes. Each node in a linked list has two components: a value and a pointer to the next node. The first node in a linked list is called the head and the last node is called the tail. The tail node has a null pointer as its next node.

In PHP, we can create and manipulate linked lists using classes and objects. For example, we can define a class for a node as follows:

// Define a class for a node
class Node {
// Declare the value and the next properties
public $value;
public $next;

// Construct a node with a given value and a null next pointer
public function __construct($value) {
$this->value = $value;
$this->next = null;
}
}

To create a linked list, we can instantiate nodes and link them together using their next pointers. For example, we can create a linked list of three numbers as follows:

// Create three nodes with values 1, 2, and 3
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(3);

// Link the nodes together
$node1->next = $node2;
$node2->next = $node3;

// Set the head of the linked list to the first node
$head = $node1;

To access an element in a linked list, we have to traverse the list from the head until we find the element or reach the end of the list. For example, to get the third element in the linked list, we can write:

// Get the third element
$current = $head; // Start from the head
$count = 0; // Keep track of the number of nodes visited
$third = null; // Initialize the third element to null

// Loop until the end of the list or the third element is found
while ($current != null && $count < 3) {
// If the count is 2, then we have reached the third element
if ($count == 2) {
// Set the third element to the current node's value
$third = $current->value;
// Break out of the loop
break;
}
// Otherwise, move to the next node and increment the count
$current = $current->next;
$count++;
}

To modify an element in a linked list, we have to traverse the list until we find the element and then change its value. For example, to change the second element in the linked list to 10, we can write:

// Change the second element
$current = $head; // Start from the head
$count = 0; // Keep track of the number of nodes visited

// Loop until the end of the list or the second element is found
while ($current != null && $count < 2) {
// If the count is 1, then we have reached the second element
if ($count == 1) {
// Change the current node's value to 10
$current->value = 10;
// Break out of the loop
break;
}
// Otherwise, move to the next node and increment the count
$current = $current->next;
$count++;
}

Linked lists have some advantages and disadvantages as a data structure. Some of the advantages are:

  • Linked lists are dynamic and can grow or shrink as needed
  • Linked lists can store values of different types and sizes
  • Linked lists can be easily inserted or deleted from anywhere in constant time

Some of the disadvantages are:

  • Linked lists do not allow random access to any element in linear time
  • Linked lists require extra space for storing pointers
  • Linked lists can be difficult to implement and debug

Linked lists are suitable for situations where we need to store a variable number of elements that are accessed sequentially and frequently inserted or deleted. Some examples of common use cases for linked lists are:

  • Storing a queue or a stack of values
  • Storing a polynomial or a sparse matrix
  • Storing a playlist or a history of actions

Binary Trees

A binary tree is a data structure that stores a collection of values of any type in a hierarchical structure. Each value in a binary tree is stored in a node that has up to two children: a left child and a right child. The topmost node in a binary tree is called the root and the nodes that have no children are called leaves.

In PHP, we can create and manipulate binary trees using classes and objects. For example, we can define a class for a node as follows:

// Define a class for a node
class Node {
// Declare the value and the left and right properties
public $value;
public $left;
public $right;

// Construct a node with a given value and null left and right pointers
public function __construct($value) {
$this->value = $value;
$this->left = null;
$this->right = null;
}
}

To create a binary tree, we can instantiate nodes and link them together using their left and right pointers. For example, we can create a binary tree of four numbers as follows:

// Create four nodes with values 1, 2, 3, and 4
$node1 = new Node(1);
$node2 = new Node(2);
$node3 = new Node(3);
$node4 = new Node(4);

// Link the nodes together
$node1->left = $node2;
$node1->right = $node3;
$node2->left = $node4;

// Set the root of the binary tree to the first node
$root = $node1;

To access an element in a binary tree, we have to traverse the tree from the root until we find the element or reach a leaf. There are different ways to traverse a binary tree, such as pre-order, in-order, or post-order. For example, to get the elements in pre-order (visit the root, then the left subtree, then the right subtree), we can write:

// Get the elements in pre-order
function preOrder($node) {
// If the node is null, return
if ($node == null) {
return;
}
// Otherwise, print the node's value
echo $node->value . " ";
// Then recursively traverse the left subtree
preOrder($node->left);
// Then recursively traverse the right subtree
preOrder($node->right);
}

// Call the function with the root node
preOrder($root); // Prints 1 2 4 3

To modify an element in a binary tree, we have to traverse the tree until we find the element and then change its value. For example, to change the third element in pre-order (which is 4) to 10, we can write:

// Change the third element in pre-order
function changeThird($node, $count) {
// If the node is null or the count is zero, return
if ($node == null || $count == 0) {
return;
}
// Otherwise, decrement the count by one
$count--;
// If the count is zero, then we have reached the third element
if ($count == 0) {
// Change the node's value to 10
$node->value = 10;
// Return from the function
return;
}
// Otherwise, recursively traverse the left subtree with the updated count
changeThird($node->left, $count);
// Then recursively traverse the right subtree with the updated count
changeThird($node->right, $count);
}

// Call the function with the root node and an initial count of three
changeThird($root, 3); // Changes the value of node4 to 10

Binary trees have some advantages and disadvantages as a data structure. Some of the advantages are:

  • Binary trees are flexible and can represent different kinds of data and relationships
  • Binary trees can support efficient search, insertion, and deletion operations if they are balanced or ordered
  • Binary trees can be used to implement other data structures such as heaps or binary search trees

Some of the disadvantages are:

  • Binary trees can be complex and difficult to implement and debug
  • Binary trees can take up more space than linear data structures due to pointers
  • Binary trees can be slow to traverse or access elements if they are unbalanced or unordered

Binary trees are suitable for situations where we need to store hierarchical or non-linear data that can be searched or manipulated efficiently. Some examples of common use cases for binary trees are:

  • Storing expressions or equations that can be evaluated or simplified
  • Storing hierarchical data such as file systems or organizational charts
  • Storing sorted data that can be searched or modified quickly using binary search or self-balancing algorithms

In this post, we have learned about three common data structures that are widely used in programming: arrays, linked lists, and binary trees. We have seen what they are, how they work, and how to use them in PHP. We have also discussed their advantages and disadvantages and some examples of their applications.

Here are some key takeaways and tips from this post:

  • Data structures are the ways of organizing and storing data in memory so that they can be accessed and manipulated efficiently
  • Arrays are simple and efficient data structures that allow random access to any element in constant time, but they have a fixed size and cannot be resized dynamically
  • Linked lists are dynamic and flexible data structures that allow easy insertion and deletion of elements from anywhere in constant time, but they do not allow random access to any element in linear time
  • Binary trees are hierarchical and versatile data structures that can support efficient search, insertion, and deletion operations if they are balanced or ordered, but they can be complex and difficult to implement and debug
  • Choosing the right data structure for a given problem depends on various factors such as the type, size, and frequency of the data, the operations that need to be performed on the data, and the trade-offs between speed, memory, and complexity

I hope you have enjoyed this post and learned something new. If you have any questions or feedback, please feel free to leave a comment below.

Thank you for reading!

--

--