在数组中查找匹配变量

时间:2015-01-07 21:11:26

标签: php

我想通过比较两个数组并报告结果来确定$today是否为已知的非工作日或假日。我不知道ifelseif结构中的内容,以便比较数组中的变量是否与$today匹配:

<?php
// Date & Time
$timeadjust = '-5 hours';
$today_long = date('l, d F Y', strtotime($timeadjust));
$today = date('m-d', strtotime($timeadjust));
$today_day_name = date('l', strtotime($timeadjust));
// Normal Non-Working Days
$saturday = 'Saturday';
$sunday = 'Sunday';
// 2015 Holidays
$new_years_day = '01-01';
$fourth_of_july = '07-04';
$thanksgiving = '11-26';
$thanksgiving_friday = '11-27';
$christmas_eve = '12-24';
$christmas = '12-25';
$new_years_eve = '12-31';
// Normal Non-Working Day Array
$no_work = array($saturday,$sunday);
// Holiday Array
$holiday = array($new_years_day,$fourth_of_july,$thanksgiving,$thanksgiving_friday,$christmas_eve,$christmas,$new_years_eve);
// Compare Today To Normal Non-Working Day & Holiday Arrays To Determine If Today Is Normal Non-Working Day Or Holiday
if ($today_day_name = $no_work) {$operating = 'CLOSED';}
elseif ($today = $holiday) {$operating = 'CLOSED';}
else {$operating = 'OPEN';}
// Display Result Of Comparison & Report Operating Status
echo '<h3>Today is&nbsp;'.$today_long.'.&nbsp;We are&nbsp;'.$operating.'&nbsp;today!</h3>';
?>

1 个答案:

答案 0 :(得分:1)

对于您正在做的事情,您可以使用in_array()来测试该值是否在所选数组中 -

// Compare Today To Normal Non-Working Day & Holiday Arrays To Determine If Today Is Normal Non-Working Day Or Holiday
if (in_array($today_day_name, $no_work)) {
    $operating = 'CLOSED';
} elseif (in_array($today, $holiday)) {
    $operating = 'CLOSED';
} else {
    $operating = 'OPEN';
}

EXAMPLE

在原始代码中,您还分配而不是测试 -

if($foo = $bar) // one equals sign assigns
if($foo == $bar) // two equals signs compares
if($foo === $bar) // three equals signs tests for equivalency, does it match value and type?

因为您分配的if语句总是评估为true。