Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

PHP Arrays Explained

Introduction to the PHP array

One of the fundamentals of programming is the array type which when it comes to PHP can have some variation in structure. Most commonly is the numerically indexed array and the associative array, both of which can be multi-dimensional if required. Array’s are responsible for holding structured data, to be utilized throughout your application in a range of circumstances.

As the writers on PHP docs describe it –

“An array in PHP is actually an ordered map. A map is a type that associates values to keys.”

Reference: PHP Arrays Documentation

In general, a PHP array can have any type of value, which gives a huge range of diversity. But the key, on the other hand, can only be an integer or a string. Apart from objects, key’s of which aren’t of these two types will be automatically cast to either an integer or a string.

PHP arrays are vastly flexible in the sense that you can have a mixed key structure, this is where values have integer keys and string keys. I know, that sounds strange but I imagine it has its uses!

I know there are many articles out there guiding learners through the syntax of PHP arrays. But what I want to do is allow the reader not only to learn the syntax but to visualize the array too. Being able to visualize an array in the mind serves a world of difference to any developer. Both on the development side and on the debugging side.

But not just this, it’s worth exploring some of the key characteristics of the PHP array type that will give some insight into how it works. So let’s have a look at a general view of PHP array characteristics.

PHP Array Characteristics

Across all of the different styles of arrays (indexed, associative, multidimensional) there are some general common principles on how they function. Let’s break them down

  • They store keys & values just like any other programming language.
  • Although we have different styles of arrays in PHP (indexed/associative), PHP doesn’t actually differentiate between the two. It’s essentially only us humans that do!
  • PHP Arrays can have mixed keys, meaning that you can have a value mapped to the integer 1 and another value mapped to a string named “one”, all in the same array!
  • Keys can be only of two types, integer, and string, but values can be of any type.
  • There are two ways you can create an array since PHP 5.4, one is by using array(1,2,3,4) and the other by using [1,2,3,4] – We will see more on this later.
  • An array in PHP is somewhat different to other languages such as C# or Java. It doesn’t have accessible properties from the array type itself and therefore depends on other functions to get these properties such as the length/count. A quick way of explaining this is in PHP, to get the count of an array you would have to use count($arrayVariable) where in Java, you would use the arrayVariable.length syntax. PHP has many of these functions that help with getting properties or interacting with the array.
  • PHP arrays can nest further arrays inside them, morphing into what we humans call a multidimensional array.
  • PHP arrays are a breeze to use, populating or depopulating data can be done in a variety of ways, some of which is the commonly known push, pop methods.
  • They can also be iterated over in a range of ways too!
  • There is no maximum limit to the size of an array in PHP. This essentially allows as many elements as possible until the memory maxes out!
  • PHP arrays are perfect for both large and small amounts of data. I’ve heard a misconception before that they are only useful for database query results, but this is simply not true.

My apologies if the above points are a bit of information overload, but the insight is necessary to understand the true flexibility.

In the following contents, the numerically indexed, associative, and multidimensional arrays will be explored. Some of which will be in basic form and some that are of a more advanced state.

Working Examples

Syntax Style

Before we start, as previously stated, there are two ways of creating and array.

The first is for any PHP Version (which is essentially the old style) 

$myArray = array();

The second is for PHP Version 5.4+

$myArray = [];

I was undecided about which style to use for the examples in this article, but I did some research on version usage.

Packagist have a yearly statistics blog post analyzing which users who used Composer to install packages from their packages website had which version of PHP. This gives a good idea of what version the world is using.

If you take a look at the below statistics from Packagist’s blog, we can see that pretty much most users are on PHP 5.6 or higher.

PHP Version Usage 2019 – Credit: https://blog.packagist.com/php-versions-stats-2019-1-edition/

Even if we look back further to their analysis in 2018, there is a tiny amount of users who have 5.3 installed.

PHP Version Usage 2018-11 – Credit: https://blog.packagist.com/php-versions-stats-2019-1-edition/

So with these statistics, I decided to use the later syntax style (5.4+) of creating an array.

Examples

Now to get our hands messy with some array syntax and visualize the virtual contents of an array variable.

Numerically Indexed Arrays


Numerically Indexed Example 1

The first example is fairly straight forward, pushing in integer values, nothing to fancy.

$mySimpleArray = [1,2,3,4];

Output Visual

When we print this array, we can see that keys have automatically been mapped to the values in incrementing order.

Numerically Indexed Example 2

Let’s try a mixed type array

$myArray = [1,"two",true,false];

Output Visual

As we discussed earlier, the values of a PHP array can be of any type, the output visual of this array shows that this is true.

Accessing values from the array

With a numerically indexed array we can access the values by their corresponding index. For example, let’s get the value of “two”.

echo $myArray[1]; // outputs two

Associative Arrays


In the following examples, some slightly different syntax is used to assign keys to values within the array.

Have a look at the below diagram to understand what the syntax is doing.

Associative Arrays Example 1

With an associative array we can define the keys by a string value. Giving some identifying name to each value. This is especially good for usage with database query results because the associative key can be the corresponding column name.

$myArray = ["myAssociativeKey1" => "myValue1", "myAssociativeKey2" => "myValue2"];

Visual Output

As we can see in the output, we have mapped our own custom keys to the values, and the variable is created.

Associative Arrays Example 2

Because PHP doesn’t consider an associative or numerically indexed array a different type, we can do exactly the same thing as we did earlier. Let’s create a mixed value type of associative array.

$myArray = ["myAssociativeKey1" => "myValue1", "myAssociativeKey2" => 1,
            "myAssociativeKey3" => false, "myAssociativeKey4" => true];

Visual Output

Accessing values from the array

Now that we are using associative keys, let’s grab the value of ‘myValue1’

echo $myArray["myAssociativeKey1"] // outputs myValue1

Multidimensional Arrays


This is where arrays get a fairly more complex, nesting comes into play and so an array can hold another array of values making it a multidimensional array.

Multidimensional Indexed Example 1

In the first example, we use an associative key with an array as it’s value.

$myMultidimensionalArray = ["dimension1" => ["myKey" => "myValue"]];

Visual Output

As we can see from the output, the key ‘dimension1’ as a value of another array which subsequently holds it’s own key and values.

Multidimensional Indexed Example 2

In this example we throw all of the preceding examples together, showing the true flexibility of the multidimensional style in PHP. It will include associative key and values, numerically indexed and values and dimensions with nested arrays.

$myMultidimensionalArray = ["myKey1" => "myValue", 
            2,
            "dimension1" => ["myKey1" => "myValue1"],
            "dimension2" => [1,2,3,4,5],
            "dimension3" => ["mySubDimension" => ["mySubSubDimension" => [5,6,7,8] ,2,3,4]],
            true,
            false,
            ];

Visual Output

As you’ll probably agree, it looks extremely messy but, of course, it’s showing its true flexibility. Being able to be numerically indexed, associative, and having multiple dimensions at the same time.

Accessing values from the array

With this more diverse array, we need to be careful that we use the exact keys in the right order. Let’s print the array nested inside with the key of ‘mySubSubArray’.

print_r($myMultidimensionalArray["dimension3"]["mySubDimension"]["mySubSubDimension"]); // outputs Array ( [0] => 5 [1] => 6 [2] => 7 [3] => 8 )

Summary

I hope this explainer helps you understand the traits of PHP’s style of arrays. As explored, they have the utmost flexibility. Being able to hold any types as values, multiple key types, and the ability to nest and nest, potentially producing humongous multidimensional arrays.

This article also shows the flexibility of accessing or getting values from an array too. Whether it be by using integer indexes or associative string keys.

If you’re interested in learning more about PHP arrays, here are some articles I’ve written in the past –

  • 5 Ways To Loop Through An Array In PHP
  • How To Add To Array In PHP

The post PHP Arrays Explained appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

PHP Arrays Explained

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×