Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
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
€8.99 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 : 9781786463890
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Slovakia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 110.97
PHP Microservices
€36.99
PHP 7 Data Structures and Algorithms
€36.99
Mastering PHP 7
€36.99
Total 110.97 Stars icon
Banner background image

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

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela