Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP

Jeff Lemay
Jeff Lemay
14,266 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,266 Points

Yes, that works great. Thanks for the help!