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 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

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;
  }
}