Why use PHP for Data Structure?

A lot of individuals have criticized the PHP language and trust me when I say this, I DON'T BLAME THEM!. Yes I don't because PHP in the past has been so slacked by un-professionals who claim to know the language at first hand. As a PHP developer, I have studied the language in and out and discovered that PHP can work well as other Object Oriented Programming language.

Since most of the application we build with PHP has a lot to do with Data, why not we focus more on how to process such data instead of manually spitting directly from the database.

In this short blog I will give you an overview on how to use PHP to develop a simple linked list. For the sake of this tutorial I will be minimal to go back to the dependency of PHP 5. But first of all I will show you the improved syntax in PHP 7.

Nodes.

What is a Node? A node is a basic unit of a data structure, such as a linked list or tree data structureNodes contain data and also may link to other nodes. Links between nodes are often implemented by pointers. 

PHP 7 Syntax of a Node:

<?php

class Node {

    public $data;

    public Node $next;

    public function __construct($data) {

        $this->data = $data;

        $this->next = null;

    } 

}

 

PHP 5 Syntax:

<?php

class Node {

    public $data;

    public $next;

    public function __construct($data) {

        $this->data = $data;

        $this->next = null;

    } 

}

Now the question is how do you use a node? Since a node is a pointer then we can say that we will point each object to another object. The next object can be null as you can see from the constructor.

$e1 = new Node("Mon");

$e2 = new Node("Tue");

$e3 = new Node("Wed");

// connecting $e1 to $e2 and $e2 to $e3

$e1->next = $e2;

$e2->next = $e3;

echo $e2->next->data; // output: "Wed"

 

There you have it guys in the next tutorial I will show you how to integrate this in a Linked List.