1. 25
    Create a key/value store within a PHP array
    2m 19s

Create a key/value store within a PHP array

Mark Shust
InstructorMark Shust
Share this video with your friends

Social Share Links

Send Tweet

Expanding on PHP arrays, you can create keys within them to store multi-dimensional, complex data.

Instructor: [0:00] It's time to finally start building out our post into an array. When prototyping in the app, it's common to hard code elements so you can just get things moving without relying on a database connection. We will do this just with our posts. [0:16] First, we will remove our tags variable, as this will later be derived from our post data. We can also remove the hasPost variable since we are not currently using it. Let's create a new post variable, and we'll assign it to an empty array.

[0:36] 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 post -- title and content. We'll store each one within its own key value assignment.

[0:52] Let's set a new title index. We will, again, use the => sign symbol just like we in the foreach statement. Then we will define the value of this index, which will just be "How to Learn PHP." Then we will type a comma and then define our second index content. This will be our main blog content. For now, we will just set this equal to "This Is How You Learn PHP."

[1:24] Rather than using a foreach loop, we can also directly display the contents from an array using what's called the bracket notation. Rather than using this foreach statement, let's go ahead and just remove this. We will replace it with an <h3> tag.

[1:40] Within here, let's just echo out the post variable. After post, we will tack on a left and right bracket, and then we can call the title as a string. Calling an array just like this refers to the value for title, which would be "How to Learn PHP." We can do the same thing for content, and we will just output this within a <p> tag.

[2:09] When saving this file and refreshing, we will see both the title outputted as well as the content.