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 Paginating a List: Controller Adjusting Invalid Numbers

IF statement

The $numbers array in the code below contains one thousand numbers. I need to count how many of these numbers fit into each of the following categories: (a) how many of them are between 1 and 1000 inclusive, (b) how many of them are less than 1, and (c) how many of them are greater than 1000. I have created a foreach loop to look at each number one after the other, but right now it’s treating every number like it belongs in all three categories. Modify the code below so that the counts are correct.

<?php

require_once('model.php');
$numbers = get_numbers();



    $count_less_than_one           = 0;
    $count_between_one_and_thousand = 0;
    $count_greater_than_thousand    = 0;

    foreach ($numbers as $number) {


        $count_less_than_one += 1;


        $count_between_one_and_thousand += 1;


        $count_greater_than_thousand += 1;


    }



include('view.php');
?>

** ... And this is my Code :| Whats Wrong?** ** it doesnt work even with equal sign >= or <= **

<?php

require_once('model.php');
$numbers = get_numbers();



    $count_less_than_one           = 0;
    $count_between_one_and_thousand = 0;
    $count_greater_than_thousand    = 0;

    foreach ($numbers as $number) {
      if($number < 1){
        $count_less_than_one += 1;
      }
      if(1 < $number < 1000){
        $count_between_one_and_thousand += 1;
      }
      if($number > 1000){
        $count_greater_than_thousand += 1;
      }

    }



include('view.php');

?>

3 Answers

Oh, I didn't realize this was directly related to an existing challenge; There's two things I notice:

Your logic to get a number between 1 and 1000 inclusively needs to be >= and <= assertions.

Also, not remembering that condition syntax being valid in PHP (but it is for some languages), I did $number >=1 && $number <= 1000 as my condition to meet condition (a).

I just completed the challenge to make sure my advice is accurate. I'd also recommend doing ++ instead of +=1

Hi, @Amit:

I would try wrapping at the beginning of the loop dealing with the $numbers an is_numeric() condition & I would also check if $numbers is in fact an array via is_array().

I would also consider switch statement be used instead.

Thank You Kevin! its fine now