Welcome to today's session on "Multidimensional Arrays and Their Traversal in PHP". Multidimensional arrays in PHP allow you to store arrays within each index instead of single elements. Think of it as an 'apartment building' with floors (outer array) and apartments on each floor (inner array). Our goal today is to build a solid understanding of these 'apartment buildings' and how to handle them effectively in PHP.
To create a multidimensional array in PHP, we use arrays of arrays. Here is an example demonstrating how to create and work with 2D arrays.
All indices in PHP arrays are 0-based. Suppose you want to visit an apartment on the second floor (index 1
) and deliver a package to the first unit (index 0
) in this building. Here's how you can do it:
By using the indices [1][0]
, you can access the value 4
. The number 1
refers to the second inner array, while 0
refers to the first element in that array.
We can visit every floor (outer array) and every apartment on each floor (inner array) using nested loops.
Continuing with the apartment-building analogy, suppose there is a task to replace the old locker code (the second element in the first array) with a new one. Here's how we can do this:
PHP offers simple functions such as count()
to manage multidimensional arrays and determine the number of rows (floors) and columns (units on each floor):
To add a new row or column to a 2D array in PHP, you can manipulate the array structure dynamically. Here is how to add a new row:
Adding a New Row
To remove a row or column, you can rearrange the elements of the array:
Removing a Column
Sometimes, when we visit every apartment on each floor, we might need to move to the next floor midway. break
can help us exit the current loop, while continue
allows us to skip the current iteration and move to the next one.
Here, as soon as Exit Floor
is found on a floor, the loop exits, and no further units on that floor are visited. However, all other units are processed as before.
Using continue
in a similar scenario can skip over specific units without leaving the loop:
In this case, when Exit Floor
is encountered, the continue
statement skips printing Exit Floor
and continues to the next apartment on the floor, meaning the loop does not stop entirely.
Great work! Today we explored various operations on multidimensional arrays, from creating them to updating and traversing them. You also learned how to add and remove rows and columns and how break
and continue
can control flow in nested loops.
Practice solidifies learning! Your next adventure awaits in our upcoming practical exercises, where you'll apply these concepts to multidimensional arrays in PHP. Happy coding!
