Owen Parsons Owen Parsons - 4 years ago 65
PHP Question

Can I use an 'or' logical operator (or something similar) within a case of the switch function?

I have this code and it doesn't work because it echo's "23" when it should echo "24" (because it's February now).

I know I can break up the or's into other case's, that way it works. I was just wondering if there is a way to use an 'or' or something similar in this situation to help tidy up even more.

<?php

$paymentday = null;

switch ($paymentday){
case date('M') == "Jan" or
date('M') == "Feb" or
date('M') == "Mar" or
date('M') == "Apr" or
date('M') == "May" or
date('M') == "Jul" or
date('M') == "Aug" or
date('M') == "Okt" or
date('M') == "Nov":
$paymentday = "24";
break;
case date('M') == "Jun":
$paymentday = "23";
break;
case date('M') == "Sep":
$paymentday = "22";
break;
case date('M') == "Dec":
$paymentday = "21";
break;
}

echo $paymentday;
?>

Answer Source

What you suggest is not possible the way you try, but take a look at this simple example:

<?php
$paymentday = null;
switch (date('M')){
    case "Jan": 
    case "Feb":
    // ...
        $paymentday = "24"; 
        break;
    case "Jun":
        $paymentday = "23";
        break;
    case "Sep":
        $paymentday = "22";
        break;
    case "Dec":
        $paymentday = "21";
        break;
}
echo $paymentday;

Or, easier and more robust:

<?php
$paymentday = null;
switch (date('M')){
    case "Jun":
        $paymentday = "23";
        break;
    case "Sep":
        $paymentday = "22";
        break;
    case "Dec":
        $paymentday = "21";
        break;
    default: 
        $paymentday = "24"; 
}
echo $paymentday;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download