2

Possible Duplicate:
How to use a switch case ‘or’ in PHP?

I want to do a test using switch, this is the code I wrote:

<?php

    $moisActuelle = date("n");
    switch($moisActuelle)
    {
        case 1 || 2 || 3 : 
             echo'L\'hiver';
             break;
        case 4 || 5 || 6 : 
             echo'Le printemp';
             break;
        case 7 || 8 || 9 : 
             echo'L\'été';
             break;
        case 10 || 11 || 2 : 
             echo'L\'automne';
             break;

    }

?>

but this code is always execute the first case whatever the $moisActuelle is.

Community
  • 1
  • 1
Renaud is Not Bill Gates
  • 1,684
  • 34
  • 105
  • 191
  • 1
    See this question: http://stackoverflow.com/questions/207002/how-to-use-a-switch-case-or-in-php – krx Nov 08 '12 at 19:25

3 Answers3

4
switch($moisActuelle)
{
    case 1: 
    case 2: 
    case 3: 
         echo'L\'hiver';
         break;
}

Switch statement will look for the first true case and after that statement will continue to perform all actions until find break or default

Denis Ermolin
  • 5,530
  • 6
  • 27
  • 44
2

I'm not sure if you can do it like that, but here's one way:

<?php

    $moisActuelle = date("n");
    switch($moisActuelle)
    {
        case 1:
        case 2:
        case 3: 
             echo'L\'hiver';
             break;
        // etc
    }

?>
tigrang
  • 6,767
  • 1
  • 20
  • 22
0

I had prefer to use such way:

<?php
    $decisionTable = array(
        '1' => 'L\'hiver',
        '2' => 'L\'hiver',
        '3' => 'L\'hiver',

        '4' => 'Le printemp',
        '5' => 'Le printemp',
        '6' => 'Le printemp',

        '7' => 'L\'été',
        '8' => 'L\'été',
        '9' => 'L\'été',

        '10' => 'L\'automne',
        '11' => 'L\'automne',
        '12' => 'L\'automne',
    );

    $moisActuelle = date("n");
    echo $decisionTable[$moisActuelle];
?>

Or, if you want use swicth:

<?php

    $moisActuelle = date("n");
    switch(true)
    {
        case in_array($moisActuelle, array(1, 2, 3)): 
             echo'L\'hiver';
             break;
        case in_array($moisActuelle, array(4, 5, 6)): 
             echo'Le printemp';
             break;
        case in_array($moisActuelle, array(7, 8, 9)): 
             echo'L\'été';
             break;
        case in_array($moisActuelle, array(10, 11, 12)): 
             echo'L\'automne';
             break;
    }

?>
Vladimir Posvistelik
  • 3,843
  • 24
  • 28