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

Having trouble with task 3 of Collections Challenge Task in OOP PhP

I get an error saying I need to consider both "roof_color" and "wall_color" and check them against the parameter $color.

--- Php public function filterHouseColor($color) { $output = array(); foreach($this->houses as $dwelling) { if ($dwelling->roof_color == $color || $dwelling->wall_color == $color) { $output[] = $dwelling; } return $output; }

}

The previous two tasks are acceptable, but I cannot figure out what is wrong with my conditional statement. Cheers

index.php
<?php

// add code below this comment

class Subdivision 
{
  public $houses = array();

  public function filterHouseColor($color) 
  {
    $output = array();
    foreach($this->houses as $dwelling) {
      if ($dwelling->roof_color == $color || $dwelling->wall_color == $color) {
        $output[] = $dwelling;
      }
      return $output;
    }
  }
}
?>

2 Answers

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there, Mike Womack ! You're doing terrific! You've understood the problem exceedingly well. This all comes down to placement. Namely, the placement of your return statement. You are returning the value a bit early. That return happens inside the foreach loop. Once a return is hit, the loop stops execution.

Right now, your code looks like this:

foreach($this->houses as $dwelling) {  // begin foreach
      if ($dwelling->roof_color == $color || $dwelling->wall_color == $color) {  // begin if
        $output[] = $dwelling;
      } // end if
      return $output;
    } // end foreach

But you meant to do this:

foreach($this->houses as $dwelling) {  // begin foreach
      if ($dwelling->roof_color == $color || $dwelling->wall_color == $color) {  // begin if
        $output[] = $dwelling;
      } // end if
    } // end foreach
    return $output; // return after the foreach has ended

Hope this helps! :sparkles:

Fantastic! Thanks so much Jennifer, I was so focussed on the conditional as the problem I missed the return statement.