Create a key:value store within a PHP array

It’s time to finally start building our posts into an array. When prototyping an app, it’s common to hard-code elements so you can get things moving without relying on a database connection, and we will do just this with our posts.

First we will remove our $tags variable for now, as these will later be derived from our post data. We can also remove hasPosts since we are not currently using it.

Let us create a $post variable, and we’ll assign it equal to an empty array:

<?php
$title = 'My Blog';
$post = [];
...

For now, this will just contain the info for a single blog post. We’ll keep things simple and just have two properties for our blog posts: title and content, and we’ll store each within its own key value assignment.

We’ll set a new title index, and we will again use the equal greater than symbol just like we used in the foreach statement, and then define the value of this index, which will be ‘How to learn PHP’.

Then, we’ll type a comma, and define our second index content. This will be our main blog content. For now, let’s just set this equal to “This is how you learn PHP.”.

<?php
$title = 'My Blog';
$post = [
    'title' => 'How to learn PHP',
    'content' => 'This is how you learn PHP.',
];
$numPosts = 10;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>

Rather than using a foreach loop, we can also directly display the contents from an array using what’s called “bracket notation”.

Let’s create a new h3 tag and echo out a call to the $post variable, but let’s tack on left and right brackets. Then, we can call the title as a string:

<h2><?= $numPostsDisplay ?></h2>
<h3><?= $post['title'] ?></h3>

And we can do the same thing for the content, displaying it in a p tag:

<?php
$title = 'My Blog';
$post = [
    'title' => 'How to learn PHP',
    'content' => 'This is how you learn PHP.',
];
$numPosts = 10;
$numPostsDisplay = "\\"$numPosts\\" posts";
?>
<h1><?= $title ?></h1>
<h2><?= $numPostsDisplay ?></h2>
<h3><?= $post['title'] ?></h3>
<p><?= $post['content'] ?></p>


Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock