mrlayance
mrlayance

Reputation: 663

PHP IF with multiple days of the week

Is this possible?

$d=date("D");
...
else if ($d=='(Thu|Fri|Sat)') {

I can get a single day of the week working.

if ($d=='Wed') {

Thanks

Upvotes: 0

Views: 358

Answers (6)

Hamish
Hamish

Reputation: 23316

$d == '(Thu|Fri|Sat)' will only match if $d matches that exact string.

You could:

  • Use a regular expression: preg_match('/^(Thu|Fri|Sat)$/', $d),
  • An array of values: in_array($d, array( 'Thu', 'Fri', 'Sat' )), or
  • Mulitple if statements: if($d == 'Thu' || $d == 'Fri' || $d == 'Sat');
  • Use a switch/case structure

Upvotes: 2

Jon Egeland
Jon Egeland

Reputation: 12613

No. For what you want, in_array() is the best choice.

if(in_array($d, array('Thu', 'Fri', 'Sat'))
  // do something if any case is true

If you want more control, switch and case are very handy and give you more control over different cases.

$d = date('D');

switch($d) {
  case 'Thu':
  case 'Fri':
  case 'Sat':
    // do something for Thu, Fri, or Sat
    break;

  case 'Mon':
    // do something only for Mon
  case 'Tue':
    // do something for Mon or Tue.
    break;
}

The first set of cases will apply the following code (up until break) if any or all of the conditions are met.

The second set will apply the code between cases Mon and Tue if Mon is true, and then continue to Tue if it is true.

switch and case can be very useful, especially here if you want real control.

Upvotes: 2

Martin.
Martin.

Reputation: 10539

Just use in_array()

if (in_array($d, array("Thu", "Fri", "Sat"))) {

}

Upvotes: 3

Starx
Starx

Reputation: 78991

Why can't you use or or ||?

else if ($d=='Thu' || $d=='Fri' || $d=='Sat') {

If you dont want to stick to simplicity then use preg_replace()[docs]

preg_match('^(Thu|Fri|Sat)$', $yourtext, $matches, PREG_OFFSET_CAPTURE);
if(count($matches)) {
    /// found
}

Upvotes: 2

Shattuck
Shattuck

Reputation: 2780

You could use the OR operator:

else if ($d=='Thu' || $d=='Fri' || $d=='Sat') {

Upvotes: 2

Iznogood
Iznogood

Reputation: 12843

Try

if(in_array($d, array('Thu', 'Fri', 'etc'))){
}

Or with ||

if($d == 'Thu' || $d == 'Fri' || etc)

Upvotes: 1

Related Questions