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 Object-Oriented PHP Basics Building a Collection Collection Objects

I don't understand 3/3 task , please help.

I don't understand what im getting from collection, i mean i know that roof_color and wall_colors are in collection , but i tried few options and it won't work.. can someone explain pls.

index.php
<?php

// add code below this comment

class Subdivision {
    public $houses;

  public function filterHouseColor($color){

  }
}

?>

1 Answer

Spenser Hale
Spenser Hale
20,778 Points

Hello Boban Rajovic,

TLDR: Check bottom example

$this->houses return an array of objects. In each house object it has property roof_color and wall_color. So you need to loop over houses property and either collect or filter out so the collection only contains houses with roof_color or wall_color of the color parameter.

Filter Example:

See: PHP Docs on array_filter

<?php
class Subdivision {
  public $houses;
  public function filterHouseColor($color) {
    return array_filter($this->houses, function($house) use($color) {
        return $house->roof_color === $color || $house->wall_color === $color;
    });
  }
}

Collect Example:

See: PHP Docs on foreach structure

<?php
class Subdivision {
  public $houses;
  public function filterHouseColor($color) {
      // Variable to store matches
      $matches = [];
      // Loop through collection setting object as local variable $house
      foreach($this->houses as $house) {
        // Check if either property matches $color
        if($house->roof_color === $color || $house->wall_color === $color) {
          // If matched add to matches collection
          $matches[] = $house;  
        }
      }
      // return the matches collection.
      return $matches;
  }
}