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 a typical array? Let us explore some more examples. Consider the following:

$mixedArray = [];
$mixedArray[0] = 200;
$mixedArray['name'] = "Mixed array";
$mixedArray[1] = 10.65;
$mixedArray[2] = ['I', 'am', 'another', 'array'];

It is a PHP array that we use on a daily basis; we do not define the size and we are storing integers, a floating point number, a string, and even another array. Does it sound odd or is it just a super power of PHP? We can look at the definition from http://php.net.

 

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

 

So a PHP array has got real super powers and it can be used for all possible data structures such as list/vector, hash table, dictionary, collection, stack, queue, doubly linked list, and so on. It seems that the PHP array has been built in such a way that it is either optimized for everything or it is not optimized for anything. We will explore that in this chapter.

If we want to categorize the array, then there are mainly three types of arrays:

  • Numeric array
  • Associative array
  • Multidimensional array

We are going to explore each type of array with some examples and explanations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset