Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Jeff Lemay
Jeff Lemay
14,268 Points

Referencing Keys in an Array

Hello Treehouse,

I've hit a wall trying to finish a personal project and I'm hoping someone can provide some guidance.

I'm building something similar to the Shirts Catalog in the php project; using arrays to show a list of different items. In the Creating the Products Array video, Randy mentions that we are assigning a specific key to each item so we can reference them later on, something you would do with a SKU or product id.

I'm wondering how you go about accessing those values, and mainly if it is possible to access the value from within the array itself. I have to use a code multiple times within each array (key, part of a filename, and part of an image-path). Rather than copy-paste the key 2 more times, I'd like to just call upon the key and have it echo automatically.

Example Code:

$items = array();

$items["codeword"] = array(
  "file" => "codeword.doc",
  "img" => "/group/img/codeword.jpg"
$items["secrettext"] = array(
  "file" => "secrettext.doc",
  "img" => "/group/img/secrettext.jpg"

The code above is simplified, but essentially I want to replace the last two "codeword"s with a reference to the array's key. It would save a lot of time in the long-run to be able to do this, so I'm hoping it's possible.

Thanks in advance, Jeff

2 Answers

Randy Hoyt
STAFF
Randy Hoyt
Treehouse Guest Teacher

There is almost certainly a way to do what you want. It all depends on exactly where you want this to happen. Would this help? When you create the array, do something like this:

$items = array();

$code = "codeword";
$items[$code] = array(
  "file" => $code . ".doc",
  "img" => "/group/img/" . $code . ".jpg"
$items["secrettext"] = array(
  "file" => "secrettext.doc",
  "img" => "/group/img/secrettext.jpg" ...

Is that what you had in mind?

Jeff Lemay
Jeff Lemay
14,268 Points

Yes, that works great. Thanks for the help!