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 Enhancing a Simple PHP Application Refactoring the Codebase Separating Concerns: MVC

Welby Obeng
Welby Obeng
20,340 Points

explain this function line by line

Can someone explain this function line by line please

// This function receives a number as an argument.
// It returns the most popular flavors based on
// the number of likes, the most popular flavor
// first. (The number of flavors returned corresponds
// to the number in the argument.)

function get_flavors_by_likes($number) {

    $all = get_all_flavors();

    $total_flavors = count($all);
    $position = 0;

    $popular = $all;
    usort($popular, function($a, $b) {
        return $b['likes'] - $a['likes'];
    });

    return array_slice($popular, 0, $number);

}

?>

1 Answer

Daniel Leak
Daniel Leak
4,105 Points

I found usort pretty confusing. First comment on this page explains it fairly well. First variable stores the array by calling outside function. $total_flavors and $position don't even get used, they shouldn't be there. $popular is also not needed, we could get rid of it and replace it's other uses in the code with $all. We only need this

function get_flavors_by_likes($number) {   
//Define function, argument is how many flavors to display

    $all = get_all_flavors();    
//Calls a previous function to assign $flavors array to $all

    usort($all, function($a, $b) {
        return $b['likes'] - $a['likes']; 
    });

usort will compare each item in the array $all, each time an item is compared to another they will be assigned $a or $b. If the function ($b["likes"]-$a["likes"]) returns a positive number, $b will move 1 towards the top of the array, if negative it will move down and if 0 it will stay in that place. In this case when $b is a larger number than $a, it will be moved to the top of the array and we will have a descending list.

    return array_slice($all, 0, $number);
}

aray_slice displays from the array ($all), starting at the first item in the array(0), however many items we asked for in the functions argument ($number)*/