$a % $b // 返回 $a 除以 $b 的餘數
// 性質:0 <= 結果 < |$b| (PHP 中結果符號同被除數)
<?php
$items = range(1, 20); // 20 個項目
$cols = 4; // 每行 4 列
echo "<table><tr>";
foreach ($items as $index => $item) {
// 每行首列輸出
if ($index % $cols === 0) {
if ($index > 0) echo "</tr>";
echo "<tr>";
}
echo "<td>項目 $item</td>";
}
// 補齊最後一行
$remainder = count($items) % $cols;
if ($remainder !== 0) {
echo str_repeat("<td> </td>", $cols - $remainder);
}
echo "</tr></table>";
2. 分頁導航:顯示當前頁附近頁碼
<?php
function pagination(int $currentPage, int $totalPages, int $window = 2): array
{
$pages = [];
$start = max(1, $currentPage - $window);
$end = min($totalPages, $currentPage + $window);
for ($i = $start; $i <= $end; $i++) {
$pages[] = $i;
}
return $pages;
}
// 另一種:固定顯示 10 頁一組
$groupSize = 10;
$currentGroup = (int)(($currentPage - 1) / $groupSize);
$startPage = $currentGroup * $groupSize + 1;
$endPage = min($startPage + $groupSize - 1, $totalPages);
3. 輪詢/輪轉分配 (負載均衡、任務分發)
<?php
$servers = ['10.0.0.1', '10.0.0.2', '10.0.0.3', '10.0.0.4'];
$requestId = 12345;
// 簡單輪詢
$selected = $servers[$requestId % count($servers)];
// 權重輪詢 (平滑加權)
$weights = [10, 20, 30, 40]; // 權重總和 100
$totalWeight = array_sum($weights);
$point = $requestId % $totalWeight;
$accumulated = 0;
foreach ($servers as $i => $server) {
$accumulated += $weights[$i];
if ($point < $accumulated) {
$selected = $server;
break;
}
}
4. 緩存分片 (Redis Cluster、一致性哈希預演)
<?php
$redisNodes = ['redis1:6379', 'redis2:6379', 'redis3:6379'];
function getNode(string $key, array $nodes): string
{
// 簡單取模分片 (生產建議 CRC32/一致性哈希)
$hash = crc32($key); // 32 位無符號
return $nodes[$hash % count($nodes)];
}
$key = "user:12345:profile";
$node = getNode($key, $redisNodes);
5. 批次處理進度條/日誌輸出控制
<?php
$total = 100000;
$batchSize = 500;
for ($i = 0; $i < $total; $i += $batchSize) {
// 處理批次...
processBatch($i, $batchSize);
// 每 10 批輸出一次進度 (減少 I/O)
if (($i / $batchSize) % 10 === 0) {
$percent = round(($i / $total) * 100, 1);
echo "進度: {$percent}% ({$i}/{$total})\n";
}
}
6. 循環數組/環形緩衝區
<?php
$buffer = [null, null, null, null, null]; // 固定大小 5
$capacity = count($buffer);
$head = 0; // 寫入位置
$count = 0; // 當前元素數
function ringPush(array &$buffer, &$head, &$count, $value, int $capacity): void
{
$buffer[$head] = $value;
$head = ($head + 1) % $capacity;
if ($count < $capacity) $count++;
}
function ringGet(array $buffer, int $head, int $count, int $index): mixed
{
if ($index < 0 || $index >= $count) return null;
// 邏輯索引 0 = 最舊元素
$physicalIndex = ($head - $count + $index + $capacity) % $capacity;
return $buffer[$physicalIndex];
}
7. 判斷奇偶、整除、質數篩選
<?php
// 奇偶
$isEven = ($n % 2 === 0);
$isOdd = ($n % 2 !== 0);
// 整除檢查 (能被 3 和 5 整除 = FizzBuzz)
if ($n % 15 === 0) echo "FizzBuzz";
elseif ($n % 3 === 0) echo "Fizz";
elseif ($n % 5 === 0) echo "Buzz";
// 簡易質數檢查 (試除法)
function isPrime(int $n): bool
{
if ($n < 2) return false;
if ($n % 2 === 0) return $n === 2;
for ($i = 3; $i * $i <= $n; $i += 2) {
if ($n % $i === 0) return false;
}
return true;
}
負數取模陷阱
<?php
// PHP: 結果符號同被除數 (被除數為負,結果為負)
echo -7 % 3; // -1 (非 2)
// Python/數學定義: 結果符號同除數 (總是非負)
// 統一為非負餘數函數
function mod(int $a, int $b): int
{
$r = $a % $b;
return $r < 0 ? $r + $b : $r;
}
echo mod(-7, 3); // 2
效能微優化
- 2 的冪次取模:
$n % 8 === $n & 7 (位運算更快)
- 循環中固定除數:編譯器優化常數傳播
- 避免在極熱路徑使用取模,改用計數器重置
總結
取模運算是將線性序列映射到循環空間的核心工具。掌握「索引 % 周期 = 位置」模式,即可輕鬆處理分頁、分組、輪詢、分片、環形結構等經典問題。注意 PHP 負數取模語義差異,跨語言移植時統一處理。
- 上一篇程序編程: PHP 調用 C/C++ 擴展開發指南:從 .so 構建到生產部署
- 下一篇程序編程: PHP 調用 C 代碼三大方案對比:FFI、C 擴展、系統調用
PHP 程式設計排行
推薦文章
- PHP 4 新函數特集:輸出緩衝控制、getcwd、set_time_limit
- PHP get_magic_quotes_gpc 檢測與相容處理:避免雙重跳脫的…
- Laravel Blade 模板 @section 系列標籤完整差異指南
- PHP 陣列排序完全指南:usort、uksort、sort 實戰範例
- PHP 移除字串最後一個字元的三種正確方法 (避免亂碼陷阱)
- PHP 刪除 HTML 標籤實用函數:deletehtml() 實現詳解
- PHP cURL 庫完整指南:從基礎到實戰的四大經典場景
- PHP 多進程檔案讀寫鎖機制完整實作
- CakePHP Session 完整配置指南:三種儲存驅動與 Component…
- PHP 陣列遍歷四大方法完整對比:foreach、while+list/each…
copyright © 萬盛學電腦網 all rights reserved