How to proceed through all cases if they are true PHP

▼魔方 西西 提交于 2019-12-04 09:28:21

try

$date = strtotime("1 October 2014"); 

     if (date('l', $date) == 'Monday'){ //case 1: If the current day is Monday
      echo "weekly<br>";
     }
     if (date('d', $date) == '01'){  //case 2: If the current day of the month is 1
      echo "monthly<br>";                       
     }
    if ( ((date('n', $date) % 3) == '1') && (date('d', $date) == '01') ){ //case 3: If a quart of the year has just passed,and we are in the first day of a new quart
      echo 'quarterly<br>';   
    }  

This is just not how switch works - it is intended to execute a single line of execution based on defined conditions - hence a 'switch'. Replace it with separate if statements.

UPDATE: solution without the use of a function:

$date = strtotime("1 September 2014");
$continue = true;

if(date('l', $date) == 'Monday'): //case 1: If the current day is Monday
    echo "weekly<br>";
else:
    $continue = false;
endif;

if(date('d', $date) == '01' && $continue):  //case 2: If the current day of the month is 1
    echo "monthly<br>";
else:
    $continue = false;
endif;

if( ((date('n') % 3) == '1') && (date('d') == '01') && $continue ): //case 3: If a quart of the year has just passed,and we are in the first day of a new quart
    echo 'quarterly<br>'; 
endif;


OLD VERSION (with the use of a function): i just coded a tiny function for you that should exactly fit your needs:

function sequencer($date_string)
{
    $date = strtotime($date_string);

    if(date('l', $date) == 'Monday'): //case 1: If the current day is Monday
        echo "weekly<br>";
    else:
        return;
    endif;

    if(date('d', $date) == '01'):  //case 2: If the current day of the month is 1
        echo "monthly<br>";
    else:
        return;
    endif;

    if( ((date('n') % 3) == '1') && (date('d') == '01') ): //case 3: If a quart of the year has just passed,and we are in the first day of a new quart
        echo 'quarterly<br>'; 
    else:
        return;
    endif;
}

sequencer("1 October 2014");

as you can see above, just call it with the date string, the strotime() is also done inside the function.

Sorry about the first answer - I never tried to do what you are doing and I apparently can't read questions properly.

Having said that, you can actually execute an echo statement with a condition to set what you want to display:

<?php

    $date = strtotime("6 October 2014");

    echo (date('l', $date) == 'Monday')?"Weekly<br>":"";
    echo (date('d', $date) == '01') == 'Monday')?"Monthly<br>":"";
    echo ( ((date('n') % 3) == '1') && (date('d') == '01') ) == 'Monday')?"Quarterly<br>":"";

?>

The above will output your desired behaviour for example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!