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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Displaying Categories

Alex Forseth
Alex Forseth
8,017 Points

strtolower($item["category"])?

foreach ($catalog as $id => $item) { if (strtolower($category) == strtolower($item["category"])

$item is essentially just an array value in a variable. My question is:

How does an array value assigned to a variable($item) determine its own value by then accessing its key? ($array_values['category']). It seems like this would force the computer to search through a list of values. What are the php rules that allow this?

2 Answers

The reason is simple its an multi dimensional array.

<?php
$catalog = []; //empty array
$catalog[101] = [
'item1'=> 'value1',
'item2'=> 'value2',
'category' => 'books',    
'author' => ['saajan','bedi']
];
$catalog[102]  =  [
'another_item'=> 'value1',
'another_item'=> 'value2',
'category' => 'movies',    
'author' => ['another','name']
];

// now  catalog is array with two more array and both of them have there own array with key of author
$catalog = [
    [
    'item1'=> 'value1',
    'item2'=> 'value2',
    'category' => 'books',    
    'author' => ['saajan','bedi']
    ],
     [
    'another_item'=> 'value1',
    'another_item'=> 'value2',
    'category' => 'movies',     
    'author' => ['another','name']
    ]
];
foreach($catalog as $key => $item){
     echo $item['category']. '<br>';
}
//  this will return books and movies

First of all, you missed the part that this:

if (strtolower($category) ==

is related to this:

$categories = array_category($catalog, $section);

From catalog.php, you called the function "array_category" with parameters "$catalog" and "$section" and stored it in a variable, like so:

$categories = array_category($catalog, $section);

You then defined the "array_category" function in functions.php, passing the "$catalog" parameter to "$catalog" and the "$section" parameter to "$category", like so:

function array_category($catalog, $category){

So basically, this code:

foreach ($catalog as $id => $item) { if (strtolower($category) == strtolower($item["category"])

means you are comparing the passed value of $section (which can be books, movies, music, etc) with the value of the "category" key in the $catalog array.