Understanding PHP Arrays

Understanding PHP Arrays

You will understand different types of arrays in PHP and how to access data from complex array dimensions.

Arrays are one of the important aspects of any programming language.

Sometimes it can be a little bit technical to grasp especially if you are just getting started in programming.
Sometimes most beginners tend to skip this part when they are starting out their journey in Programming, Trust me if you don't understand the Array principles of any programming language you are using, data structuring will be hard for you.

I struggled with this part of my journey as a PHP developer, sincerely speaking it wasn't a nice experience for me. Over the years I had to take my time to actually understand how it works and how to make the most use of it.

WHAT IS AN ARRAY?

An array is a data structure, which can be used to store a collection of data. This data can be a variable of different data types or just any kind of data at all, it doesn't have to be the same data type.

With an array, you can store a group of data as a single variable.

e.g $cars = array('BMW', 'BENZ', 'LEXUS');

In the example above, we have a variable named cars which contains a list of car companies.

Ways to Declare Variables in PHP:

In PHP, arrays are declared in two ways

  1. Using array function array() e.g array('BMW', 'BENZ', 'LEXUS');

  2. Using the square bracket syntax [ ] e.g [′BMW′,′BENZ′,′LEXUS′];

The square bracket syntax [ ] is a shorthand syntax of the array function, the two are valid, usage is totally based on the one you are comfortable with.

TYPES OF ARRAY IN PHP

  • Indexed array

//example of an indexed array

$car = array('BMW', 'BENZ', 'LEXUS');

or

$car = [′BMW′,′BENZ′,′LEXUS′];

It is called an indexed array because you access the values of the array by their indexes e.g. $car[0] // result BMW

  • Associative array:

The associative array makes use of key-value pairs: what this means is that a key is assigned a value using the arrow key. e.g

$arr = ['name'=>'Victor','age'=>20,'country'=> 'Nigeria'];

$car[′name′] // result = Victor;

  • Multidimensional array:

This is also known as an array of arrays, There are different forms of a multidimensional array, you can have a two-dimensional array, a three-dimensional array even a four-dimensional array. You can have infinite dimensions of arrays.

...n-dimension of array where n can be any number
and this is where things start to get tricky but don't worry we got this.

Arrays start to get too tricky to handle when they go beyond two dimensions,

In other to keep this article short we are only going to treat 2,3,4 dimension arrays This will help guide your understanding of destructuring any array in PHP regardless of its number of dimensions.

Examples of Multidimensional Arrays

  1. Two-dimensional Array:

// 2-dimensional array

$cars = array (array("Volvo",22,18), array("BMW",15,13),array("Land Rover",17,15));

$Cars = [ ["Volve",22, 18], ["BMW", 15, 13], ["Land Rover", 17, 15]];

To access data inside the $cars array

$cars[0] 
//result will be the first array
//["Volve",22, 18]

//$car[2] is the last array and we want to get the first data inside it
$cars[2][0] 
//result
//Land Rover
  1. Three-Dimensional Array:

    Two dimensional array seems simple but things started to get tricky from 3 dimensions and above.
    If you can understand a 3-dimensional array and how to access its data, trust me you can work with 4,5 dimensions and above.

    The dimension of an array represents the nested depth of such an array.

    We can see that in the code below

//Example of a 3-dimensional array
$cars = [
    'brands' => [
            'Toyota' => ['suv','saloon','pickup-truck'],
             'BMW' => ['suv','saloon','pickup-truck'],
            'Ford' => ['suv','saloon','pickup-truck'],
      ]
];

//using array function
$cars = array(
            'brands' => array(
                        'Toyota' => array('suv','saloon','pickup-truck'),
                        'BMW' => array('suv','saloon','pickup-truck'),
                        'Ford' => array('suv','saloon','pickup-truck'),
                        )
         );

The code above has an array with a depth of 3.
So if we trace the left square bracket key or the array function key you will notice that it appears as a major content wrapper 3 times.

The first wrapper is the parent wrapper, wrapping the brand's item

The second wrapper is wrapping the content of the brand's item

The third wrapper is wrapping the individual content of the second wrapper

Now we have understood the dimension(depth) and we can agree we have just 3

lets now extract data from these arrays

$cars['brands']['Toyota'][0] //result  == suv
$cars['brands']['BMW'][2] // result == pickup-truck

From the code above, you will notice that 3 boxes of square brackets were used to access the content of the third array. This is because the value we are trying to obtain is in the third depth(third dimension) of the array hence 3 box of square brackets is used.

The number of square bracket boxes used to fetch content from the array tells you what dept you are in an array.

if we have a 4-dimensional array the number of square bracket boxes to use will be 4 and the same goes for any dimension of the array you want to access.

Always remember to check the type of array you want to access its data, understanding the array type will help you know the right method to fetch data.

NOTE: Indexed array values are fetched by its index while associative array values are fetched by its key.

The End

You can share your contributions in the comments. if this was valuable to you in any way, like, share, and comment.

Thank you for reading.