Remember in the last blog post we talked about arrays and how arrays are initialized in PHP? This blog post continues on the same lane and describes ‘Multi-dimensional array’, a topic that we did not cover in the last part. Having discussed indexed array and associative arrays, it must be noted that multi dimensional arrays are conceptually a little different, however; if you have understood arrays well, then you will find that multi-dimensional arrays are just a walk in the park.
What are multi dimensional arrays?
As the name suggests, multi-dimensional array refers to an array that points to multiple dimensions. In simpler words, if you have arrays inside an array, then you are actually dealing with multi- dimensional arrays. Confused? Let us explain with the help of a real time scenario. Assume you run a company that has the records of every employee in every department inside an array named $company_data. The array ‘$company_data’ will have department names, name of the employee and then their Employee Ids. How will you accommodate so much data inside an array? You can have the name of the employee in an indexed array. To accommodate their employee ids, you can use an associative array. However; still you won’t be able to group them according to their departments. This is where the multi dimensional arrays come into picture. In the scenario that I mentioned, if inside the array ‘$company_name’, you have arrays of each department, and then inside the arrays of department, you can keep the employee data in associative array format. This all might seem a little too heavy to digest, but once you get the concept behind arrays, you will automatically understand the process that goes on in multi dimensional arrays.
<?php $company_date = array ( ‘IT’ => array (“Alex_IT” => “1”, “Barry_IT” => “2”, “Greg_IT” => “3”), ‘HR’ => array (“Soniya_HR” => “9”, “Mohammed_HR” => “6”), ‘Sales’ => array (“Mike_Sales” => “4”, “Nathan_Sales” => “7”) ); ?>
- PHP syntax does not rule out any number of dimensional arrays in it. So you can have four, five or even six dimensional arrays in your PHP script. However; it gets very clumsy and difficult to understand as the number on the dimension level goes higher. Therefore, in practice, you will only find two dimensional or in some cases three dimensional arrays in PHP script.
- If a problem needs more than 3 dimensions in the array, it is better to go for database tables and store the values in it in specific columns and rows. Integrating PHP with databases is a part of this course and will be covered later.
GET YOUR FREE PHP EBOOK!