Re: Switch - Case Statement Questions
| From: | Tim Streater | Date: | Fri, 16 Nov 2012 17:38:00 +0000 |
| Subject: | Re: Switch - Case Statement Questions | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-319714@lists.php.net to get a copy of this message | ||
On 16 Nov 2012 at 12:10, Omar Muhsin <mrfroasty@gmail.com> wrote:
> Hello,
>
> I was just wondering after writting the code in version 2 here below, it turns
> out in testing that it actually PHP is not validating the expressions instead
> always I get the first case.
>
> 1.Using nested if statement {THE INTENDED BEHAVIOR}:
> if ($count > 14)
> $boxes = 3;
> elseif($count > 7 && $count <= 14)
You don't need the count<=14 part as you will *only* get there if $count<=14.
> $boxes = 2;
> else
> $boxes = 1;
>
> 2. Using Switch {ALWAYS FIRST CASE!!!}
>
> // $boxes = 1;
> // switch ($count) {
> // case ($count > 14):
> // $boxes = 3;
> // break;
> // case ($count > 7 && $count <= 14):
> // $boxes = 2;
> // break;
> // case ($count <= 7):
> // default :
> // $boxes = 1;
> // break;
> // }
>
>
> Does anyone know the answer why using the Switch it always execute the first
> case ?
As has been pointed out you need switch(true).
That's a strange way of writing a switch, IMO. You should be using the if version.
--
Cheers -- Tim