Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
PHP 7 Data Structures and Algorithms
PHP 7 Data Structures and Algorithms

PHP 7 Data Structures and Algorithms: Implement linked lists, stacks, and queues using PHP

eBook
AU$36.99 AU$53.99
Paperback
AU$67.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

PHP 7 Data Structures and Algorithms

Understanding PHP Arrays

The PHP array is one of the most used data types in PHP. Most of the time we use it without considering the impact of PHP arrays in our developed code or application. It is so easy to use and dynamic in nature; we love to use PHP arrays for almost any purpose. Sometimes we do not even want to explore if there are other available solutions which can be used instead of PHP array. In this chapter, we are going to explore the positives and negatives of PHP arrays, along with how to use arrays in different data structure implementations along with boosting performances. We will start with explaining different types of arrays in PHP followed by creating fixed sized arrays. Then we are going to see the memory footprints for PHP array elements and how can we improve them along with some data structure implementations.

...

Understanding PHP arrays in a better way

PHP arrays are so dynamic and flexible that we have to think about whether it is a regular array, an associative array, or a multidimensional array, as in some other languages. We do not need to define the size and data type of the array we are going to use. How can PHP do that, while other languages like C and Java cannot do the same? The answer is very simple: the array concept in PHP is not actually the real array, it is actually a HashMap. In other words, a PHP array is not the plain and simple array concept we have from other languages. A simple array will look like this:

But, we can definitely do that with PHP. Let us check with an example:

$array = [1,2,3,4,5];

This line shows how a typical array should look. Similar types of data have a sequential index (starting from 0 to 4) to access the values. So who says a PHP array is not...

Using an array as flexible storage

So far we have seen a PHP array as a dynamic, hybrid data structure for storing any type of data. This gives us a lot more freedom to utilize an array as a flexible storage container for our data. We can mix different data types and different dimensions of data in a single array. We do not have to even define the size or type of array we are going to use. We can grow, shrink, and modify data to and from an array whenever we need to.

Not only does PHP allows us to create dynamic arrays, but it also provides us with lots of built-in functionalities for arrays. For example: array_intersect, array_merge, array_diff, array_push, array_pop, prev, next, current, end, and many more.

Use of multi-dimensional arrays to represent data structures

In coming chapters, we will talk about many different data structures and algorithms. One of the key data structures we are going to focus is the graph. We already know the definition of graph data structures. Most of the time we will be using PHP multidimensional arrays to represent that data as an adjacency matrix. Let us consider the following graph diagram:

Now if we consider each node of the graph to be a value of an array, we can represent the nodes as:

$nodes = ['A', 'B', 'C', 'D', 'E'];

But this will only give us node names. We cannot connect or create a relationship between nodes. In order to do that, we need to construct a two-dimensional array where the node names will be keys, and values will be 0 or 1 based on the interconnectivity of two nodes. Since there...

Performance comparison between a regular PHP array and SplFixedArray

One of the key questions we encountered in the last section was, why should we use SplFixedArray instead of PHP arrays? We are now ready to explore the answer. We came across the concept that PHP arrays are actually not arrays rather than hash maps. Let us run a small example code in PHP 5.x version to see the memory usage of a PHP array.

Let us create an array with 100,000 unique PHP integers. As I am running a 64 bit machine, I expect each integer to take 8 bytes each. So we will have around 800,000 bytes of memory consumed for the array. Here is the code:

$startMemory = memory_get_usage();
$array = range(1,100000);
$endMemory = memory_get_usage();
echo ($endMemory - $startMemory)." bytes";

If we run this code in our command prompt, we will see an output of 14,649,040 bytes. Yes, it is correct. The memory...

Understanding hash tables

In programming language, a hash table is a data structure which is used to make an array associative. It means we can use keys to map values instead of using an index. A hash table must use a hash function to compute an index into an array of buckets or slots, from which the desired value can be found:

As we have mentioned several times, a PHP array is actually a hash table and hence it supports associative arrays. We need to remember one thing: that we do not need to define a hash function for the associative array implementation. PHP does it internally for us. As a result, when we create an associative array in PHP, we are actually creating a hash table. For example, the following code can be considered as the hash table:

$array = []; 
$array['Germany'] = "Position 1";
$array['Argentina'] = "Position 2";
$array...

Implementing struct using a PHP array

As we already know, a struct is a complex data type where we define multiple properties as a group so that we can use it as a single data type. We can write a struct using a PHP array and class. Here is an example of a struct using a PHP array:

$player = [ 
"name" => "Ronaldo",
"country" => "Portugal",
"age" => 31,
"currentTeam" => "Real Madrid"
];

It is simply an associative array with keys as string. A complex struct can be constructed using single or more constructs as its properties. For example using the player struct, we can use a team struct:

$ronaldo = [ 
"name" => "Ronaldo",
"country" => "Portugal",
"age" => 31,
"currentTeam" => "Real Madrid&quot...

Implementing sets using a PHP array

A set is a simply a collection of values without any particular order. It can contain any data type and we can run different set operations such as union, intersection, complement, and so on. As a set only contains values, we can construct a basic PHP array and assign values to it so that it grows dynamically. The following example shows two sets that we have defined; one contains some odd numbers and the other one has some prime numbers:

$odd = []; 
$odd[] = 1;
$odd[] = 3;
$odd[] = 5;
$odd[] = 7;
$odd[] = 9;

$prime = [];
$prime[] = 2;
$prime[] = 3;
$prime[] = 5;

In order to check the existence of a value inside the set along with union, intersection, and complement operation, we can use the following example:

if (in_array(2, $prime)) { 
echo "2 is a prime";
}

$union = array_merge($prime, $odd);
$intersection = array_intersect(...

Best usage of a PHP array

Though a PHP array consumes more memory, the flexibility of using a PHP array is much more important for many data structures. As a result, we will use a PHP regular array as well as SplFixedArray in many of our data structure implementations and algorithms. If we just consider a PHP array as a container for our data, it will be easier for us to utilize its immensely powerful features in many data structure implementations. Along with built-in functions, a PHP array is definitely a must use data structure for programming and developing applications using PHP.

PHP has some built-in sorting functions for an array. It can sort using keys and values along with keeping association while sorting. We are going to explore these built-in functions in Chapter 7, Using Sorting Algorithms.

PHP array, is it a performance killer?

We have seen in this chapter how each element in a PHP array has a very big overhead of memory. Since it is done by the language itself, there is very little we can do over here, except that we use SplFixedArray instead of a regular array where it is applicable. But if we move from our PHP 5.x version to the new PHP 7, then we can have a huge improvement in our application, whether we use regular PHP array or SplFixedArray.

In PHP 7, the internal implementation of a hash table has been changed drastically and it is not built for efficiency. As a result, the overhead memory consumption for each element has gone down significantly. Though we can argue that less memory consumption does not make a code speedy, we can have a counter argument that if we have less memory to manage, we can focus more on execution rather than memory management. As...

Summary

In this chapter, we have focused our discussion on PHP arrays and what can be done using a PHP array as a data structure. We are going to continue our exploration of array features in the coming chapters. In the next chapter, we are going to focus on linked list data structures and different variants of linked list. We are also going to explore different types of practical examples regarding linked lists and their best usages.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain a complete understanding of data structures using a simple approach
  • Analyze algorithms and learn when you should apply each solution
  • Explore the true potential of functional data structures

Description

PHP has always been the the go-to language for web based application development, but there are materials and resources you can refer to to see how it works. Data structures and algorithms help you to code and execute them effectively, cutting down on processing time significantly. If you want to explore data structures and algorithms in a practical way with real-life projects, then this book is for you. The book begins by introducing you to data structures and algorithms and how to solve a problem from beginning to end using them. Once you are well aware of the basics, it covers the core aspects like arrays, listed lists, stacks and queues. It will take you through several methods of finding efficient algorithms and show you which ones you should implement in each scenario. In addition to this, you will explore the possibilities of functional data structures using PHP and go through advanced algorithms and graphs as well as dynamic programming. By the end, you will be confident enough to tackle both basic and advanced data structures, understand how they work, and know when to use them in your day-to-day work

Who is this book for?

This book is for those who want to learn data structures and algorithms with PHP for better control over application-solution, efficiency, and optimization. A basic understanding of PHP data types, control structures, and other basic features is required

What you will learn

  • Gain a better understanding of PHP arrays as a basic data structure and their hidden power
  • Grasp how to analyze algorithms
  • Implement linked lists, double linked lists, stack, queues, and priority queues using PHP
  • Work with sorting, searching, and recursive algorithms
  • Make use of greedy, dynamic, and pattern matching algorithms
  • Implement tree, heaps, and graph algorithms
  • Apply PHP functional data structures and built-in data structures and algorithms

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 26, 2017
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781786463579
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : May 26, 2017
Length: 340 pages
Edition : 1st
Language : English
ISBN-13 : 9781786463579
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
AU$249.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts
AU$349.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 203.97
PHP Microservices
AU$67.99
PHP 7 Data Structures and Algorithms
AU$67.99
Mastering PHP 7
AU$67.99
Total AU$ 203.97 Stars icon

Table of Contents

13 Chapters
Introduction to Data Structures and Algorithms Chevron down icon Chevron up icon
Understanding PHP Arrays Chevron down icon Chevron up icon
Using Linked Lists Chevron down icon Chevron up icon
Constructing Stacks and Queues Chevron down icon Chevron up icon
Applying Recursive Algorithms - Recursion Chevron down icon Chevron up icon
Understanding and Implementing Trees Chevron down icon Chevron up icon
Using Sorting Algorithms Chevron down icon Chevron up icon
Exploring Search Options Chevron down icon Chevron up icon
Putting Graphs into Action Chevron down icon Chevron up icon
Understanding and Using Heaps Chevron down icon Chevron up icon
Solving Problems with Advanced Techniques Chevron down icon Chevron up icon
PHP Built-In Support for Data Structures and Algorithms Chevron down icon Chevron up icon
Functional Data Structures with PHP Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
N/A Feb 08, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Ben de Leur Nov 23, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Good
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.