My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Understanding PHP Arrays

Understanding PHP Arrays

Anih Victor Chinecherem's photo
Anih Victor Chinecherem
·Feb 2, 2023·

5 min read

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

But this important part is what most beginners tend to skip when they are starting out their journey in Programming, trust me if you don't understand Array principles of any programming language you are using, data structuring will be hard for you. I struggled with this part in my journey as a PHP developer, sincerely speaking it wasn't a nice experience for me.

With respect to that, we will be looking into PHP Arrays.

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 type or just any kind of data at all, it doesn't have to vary. 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 contain a list of car companies.

In PHP, arrays are declared in two ways

  • Using array function array()

    array('BMW', 'BENZ', 'LEXUS');

  • Using the square bracket syntax [ ]

    ['BMW', 'BENZ', 'LEXUS'];

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

TYPES OF ARRAY IN PHP

  • Indexed array

    //this is 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 index
    **/

    $car[1] // result BENZ

  • Associative array

    The associative array makes use of keys with a value assigned to them using the arrow key.

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

    $car['name'] // result Victor

  • Multidimensional array

    This is also known as array of arrays, there are different forms of a multidimensional array and this is where things start to get tricky but don't worry we got this.

    // 2-dimensional array $cars = array ( array("Volvo",22,18), array("BMW",15,13), array("Saab",5,2), array("Land Rover",17,15) );

    //3-dimensional array using the square bracket syntax

    $faculties = [//1st dimension [//2nd dimension ['100lv', '200lv', '300lv', '400lv'],//3rd dimension ['100lv', '200lv', '300lv', '400lv'],//3rd dimension ['100lv', '200lv', '300lv', '400lv'] //3rd dimension ]//end of 2nd dimension ];//end of first dimension

    //using key-value pairs (associative array format)

    $faculties = [ 'Engineering' => [ 'Electrical' => ['100lv', '200lv', '300lv', '400lv'], 'Computer' => ['100lv', '200lv', '300lv', '400lv'], 'Chemical' => ['100lv', '200lv', '300lv', '400lv'] ] ];

    /* I believe you can trace the dimensions of the associative array above */

I believe the example above explains how the dimensional levels of an array are structured and in that same way you can have as many levels of dimension you want in your array.

The weird part

The weird and confusing part of working with arrays in any programming language is retreiving the data, and it gets more complicated when you have a lot of layered arrays stacked ontop of each other like the multidimensional array. Lets now see how to retrieve our array data

Let's retrieve some data from our multidimensional array

For us to retrieve data from an array we must understand how the array index is structured.

//lets explore the indexs of our car arrays $cars = array ( array("Volvo", 22, 18), //--> 1st index [0]

array("BMW",15,13), //--> 2nd index[1]

array("Saab",5,2), //--> 3rd index [2]

array("Land Rover",17,15) //--> 4th index[3] );

So in the code snippet above, we have a 2-dimensional car array, let me show you how to retrieve its data using the index.

Now let's return the first index of the first dimension

return  $cars[0];   /** result  [ "Volvo", 22, 18 ] **/

As you would have noticed the result of the first index was an array which was another dimension (2nd dimension) or you can call it the second layer. Here the second layer is another array with its own separate data which can also be accessed using its index.

Let's see what that means in the code below.

// let's get the second index of the second dimension array

return $cars[0][1]; // result 22

So as you would have guessed, if it were to be a 3-dimensional array we would have had 3 square brackets to access the data inside the last array, something like this $cars[0][1][2].

Retrieve arrays with keys

What if our array is in the associative array format and it's 2 or 3 dimensional how do we retrieve its data.

Let's use the associative faculty array in this example

$faculties = [ 'Engineering' => [ 'Electrical' => ['100lv', '200lv', '300lv', '400lv'], 'Computer' => ['100lv', '200lv', '300lv', '400lv'], 'Chemical' => ['100lv', '200lv', '300lv', '400lv'] ] ];

// Note: the 3-dimension array here is not in the //associative array format, it's an indexed array;

return $faculties[0] //result Undefined offset error

/* we got the undefined offset error because the array is an associative array therefore its cannot be accessed by indexing */

return $faculties['Engineering'];

/** Result
[ 'Electrical' => ['100lv', '200lv', '300lv', '400lv'], 'Computer' => ['100lv', '200lv', '300lv', '400lv'], 'Chemical' => ['100lv', '200lv', '300lv', '400lv'] ] **/

I believe with the example above you would be able to retrieve the second dimension of the array.

In this last example, I will show us how we can get the data of the last array; I'm hoping you must have guessed it by now but let us explore it anyway.

return $faculties['Engineering']['Computer'][2];

//result 300lv

The last array is an indexed array so we access the data through its index.

Summary

  • Array is a data store used to hold a group of data. Just like any other datatype, arrays are equally assigned to the computer memory by assigning it to a variable. So basically its is a datatype that holds different types of data together as a collection and this collection can be stored in the computer memory temporarily.

  • We have three types of arrays in PHP - Indexed array - Associative array - Multidimensional array

  • Associative array is in key-value pair structure and can be accessed using the array keys enclosed in a square brackets [ ].

  • Indexed array accepts only the values separated by a comma while the index is hidden. The values of an indexed array can be accessed using its index enclosed in square a bracket [ ].

That's the end of this part of the series next time we will be looking at how to sort and manipulate our array data.

I hope I was detailed enough leave a comment let me know how this helped you.