You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何优雅优化PHP中判断当前日期匹配二进制星期字符串的代码

Optimized Solution for Checking Binary Weekday String

Great question! Your existing code works perfectly, but we can strip out unnecessary overhead (like building an array of active days and using in_array()) to make it far lighter and more elegant. Here are two refined approaches, with the second being the most efficient:

Approach 1: Use a Day-to-Index Mapping (Clear & Robust)

This approach keeps an explicit mapping between weekday names and their positions in the binary string, making the code easy to read and adjust if your weekday order ever changes:

// Define the exact order of weekdays matching your binary string
$weekdayOrder = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
// Flip to create a "weekday name → index" lookup map
$dayIndexLookup = array_flip($weekdayOrder);

$binaryWeek = "1001110";
$currentDay = date('l');

// Check if the current day's position in the binary string is '1'
$isActive = isset($dayIndexLookup[$currentDay]) && $binaryWeek[$dayIndexLookup[$currentDay]] === '1';

echo $isActive ? "Current day is TRUE" : "Current day is FALSE";

Why this is better:

  • No loops needed to build an array of active days—we directly look up the current day's position.
  • Explicit mapping makes the code self-documenting, so anyone reading it can immediately see how the binary string maps to weekdays.

Approach 2: Use date('N') for Ultra-Lightweight Check

This is the most efficient method, leveraging PHP's built-in date function to skip the lookup array entirely:

$binaryWeek = "1001110";
// date('N') returns 1 (Monday) to 7 (Sunday) → subtract 1 to get 0-6 index
$currentDayIndex = date('N') - 1;

// Verify the index exists in the string, then check if the character is '1'
$isActive = isset($binaryWeek[$currentDayIndex]) && $binaryWeek[$currentDayIndex] === '1';

echo $isActive ? "Current day is TRUE" : "Current day is FALSE";

Why this is the best option:

  • Zero extra arrays or loops: We directly calculate the correct index using date('N'), which aligns perfectly with your binary string's order (Monday = first character, index 0; Sunday = last character, index 6).
  • Minimal memory usage: No intermediate arrays are created, making this the most performant solution.
  • Concise and readable: The logic is straightforward once you know date('N')'s behavior.

Important Note:

Ensure your binary string is always 7 characters long, with the first character corresponding to Monday and the last to Sunday (matching your example). If the order ever changes, you’ll need to adjust the index calculation accordingly.


内容的提问来源于stack exchange,提问作者Joel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:43:39