Welcome to the Treehouse Community
Looking to learn something new?
Jeff Lemay14,266 Points
Referencing Keys in an Array
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.
$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
Randy HoytTreehouse 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?