Create a nested or multi-dimensional array in PHP
This setup works for one post, but we are building a blog and obviously need to support multiple posts. What’s cool about PHP arrays is that you can have arrays within arrays.
Let’s create a new $posts
variable, and let’s set it equal to an empty array:
<?php $title = 'My Blog'; $posts = []; $post = [ 'title' => 'How to learn PHP', 'content' => 'This is how you learn PHP.', ];
Just like how we put each title and content on it’s own line in this $post
array, let’s open up this bracket to an empty line. Then, what we can do is take the contents of this post and paste it in as the first value to this $posts
array.
<?php $title = 'My Blog'; $posts = [ [ 'title' => 'How to learn PHP', 'content' => 'This is how you learn PHP.', ] ];
We can see that we now have an array (highlight full posts array), then an array within an array. This will allow us to store multiple posts within a single array, and is called a multi-dimensional array.
Let’s copy this first blog post, and add another one here. Be sure to separate these values with commas. We’ll change this second post to MySQL.
<?php $title = 'My Blog'; $posts = [ [ 'title' => 'How to learn PHP', 'content' => 'This is how you learn PHP.', ], [ 'title' => 'How to learn MySQL', 'content' => 'This is how you learn MySQL.', ], ];
Let’s remove our h3 and p tags at the bottom of our page, and create a new <pre>
tag. This outputs all of the text in a preformatted, or mono-spaced font. Then within it, we will create a new php tag that calls var_dump
, passing in our $posts
array. Note that we aren’t using a short echo tag here, since var_dump
automatically echos out any content that is passed to it.
Now when we refresh the page, we’ll see the full output of this $posts
array. We will see that the count of this array has 2 items, that the first item has a key of 0, and the second has a key of 1. Each of this array values is also assigned to another array, each with their own title and content keys.
<?php $title = 'My Blog'; $posts = [ [ 'title' => 'How to learn PHP', 'content' => 'This is how you learn PHP.', ], [ 'title' => 'How to learn MySQL', 'content' => 'This is how you learn MySQL.', ], ]; $numPosts = 10; $numPostsDisplay = "\\"$numPosts\\" posts"; ?> <h1><?= $title ?></h1> <h2><?= $numPostsDisplay ?></h2> <pre><?php var_dump($posts) ?></pre>