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

Javier MARQUEZ
Javier MARQUEZ
11,877 Points

Can you please verify if ,modifications, made to function array_category are a good idea? Seems more clear to me

<?php

function array_category($catalog, $category){
    $output = array();
    if ($category == null){
    return array_keys($catalog);
    return $output;
    }
    else    {
    $output = array();
    foreach ($catalog as $id => $item){
        if (strtolower($category) == strtolower($item["category"])){
            $output[] = $id;
            }       
    }
    return $output;
    }
}
Javier MARQUEZ
Javier MARQUEZ
11,877 Points

I dont seem to be able to paste my code. What an embarrassment lol. I thought I was a bit more computer literate. Sorry.

2 Answers

Hi Javier,

It's ok to put the loop in an else block if that makes more sense to you but it does add extra lines of code.

You don't have to initialize the $output variable twice. It's enough to either do it at the top or in the else block.

Also, it's not useful to have 2 return statements in a row. The second one is unreachable. So you can remove return $output that you have in your if block.

Javier MARQUEZ
Javier MARQUEZ
11,877 Points

Thanks a lot, its more clear now.