首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 新手必會經典代碼片段:迴圈、函式、表單、陣列、字串、日期時間實戰

     編輯:PHP 相關知識

掌握核心語法的經典用法,是從「會寫代碼」到「寫好代碼」的捷徑。本文精選 10 個高頻場景的標準實作模式,可直接複製適配專案。

1. 經典 for 迴圈與進階用法

<?php
// 基礎計數
for ($i = 1; $i <= 10; $i++) { echo $i; }

// 陣列索引遍歷 (效能優於 foreach)
$arr = ['a', 'b', 'c'];
for ($i = 0, $len = count($arr); $i < $len; $i++) { echo $arr[$i]; }

// 日期倒數:距離下個週一幾天
$current = time();
while (date('l', $current) !== 'Monday') {
    echo date('l', $current) . "\n";
    $current += 86400; // 1 天秒數
}
?>

2. 函式定義與呼叫標準模式

<?php
// 無參數、無回傳 (副作用型)
function logInfo(string $msg): void {
    error_log(date('Y-m-d H:i:s') . " $msg\n", 3, '/var/log/app.log');
}

// 有參數、有回傳 (純函式風格)
function calculateTotal(float $price, int $qty, float $taxRate = 0.05): float {
    return round($price * $qty * (1 + $taxRate), 2);
}

// 可變參數 (PHP 5.6+)
function sum(float ...$numbers): float {
    return array_sum($numbers);
}

// 參考傳遞修改原值
function normalizeString(string &$str): void {
    $str = trim(mb_strtolower($str, 'UTF-8'));
}
?>

3. 表單處理完整流程 (PRG 模式)

<?php
// form.php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. 驗證
    $errors = [];
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    if ($name === '') $errors['name'] = '姓名必填';
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) $errors['email'] = 'Email 格式錯誤';
    
    // 2. 成功則處理並重導向 (防重複提交)
    if (empty($errors)) {
        // 儲存資料庫、發送郵件...
        header('Location: success.php');
        exit;
    }
}
// 3. 失敗或 GET 請求:顯示表單 (保留輸入值)
?>
<form method="post">
    <input name="name" value="<?= htmlspecialchars($name ?? '') ?>">
    <?= $errors['name'] ?? '' ?>
    <input name="email" type="email" value="<?= htmlspecialchars($email ?? '') ?>">
    <?= $errors['email'] ?? '' ?>
    <button type="submit">送出</button>
</form>

4. 陣列操作高頻模式

<?php
// 陣列去重 (保留鍵名)
$unique = array_unique($arr);

// 陣列差集/交集
$newItems = array_diff($newIds, $existingIds);
$common = array_intersect($arr1, $arr2);

// 鍵值互換
$flipped = array_flip($keyValueArr);

// 陣列合併 (字串鍵後者覆蓋,數字鍵重設索引)
$merged = array_merge($defaults, $userOptions);

// 陣列分塊 (分頁、批次處理)
$chunks = array_chunk($bigArray, 100);
foreach ($chunks as $batch) { processBatch($batch); }

// 陣列隨機打亂
shuffle($arr); // 修改原陣列
?>

5. 字串處理實用片段

<?php
// 安全截取 UTF-8
$excerpt = mb_strlen($content) > 200 ? mb_substr($content, 0, 200) . '...' : $content;

// 產生 URL 友善 slug
$slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $title), '-'));

// 移除 HTML 標籤 (保留允許標籤)
$clean = strip_tags($html, '


'); // 字串模板插值 (簡易) $template = 'Hello {name}, welcome to {site}'; $rendered = strtr($template, ['{name}' => $name, '{site}' => $site]); // 多行字串 (Heredoc/Nowdoc) $sql = << '{$date}' SQL; ?>

6. 日期時間現代化操作 (DateTime 類別)

<?php
// 建立
$now = new DateTime('now', new DateTimeZone('Asia/Taipei'));
$specific = DateTime::createFromFormat('Y-m-d H:i:s', '2024-01-15 14:30:00');

// 格式化
echo $now->format('Y-m-d H:i:s'); // 2024-01-15 14:30:00

// 運算
$now->modify('+1 week');
$now->add(new DateInterval('P3D')); // 加 3 天
$diff = $now->diff($specific); // DateInterval 物件

// 比較
if ($now > $specific) { /* ... */ }

// 時區轉換
$utc = clone $now;
$utc->setTimezone(new DateTimeZone('UTC'));
?>

7. 檔案上傳安全處理

<?php
function handleUpload(array $file, string $uploadDir, array $allowedMimes = ['image/jpeg', 'image/png', 'image/gif']): ?string {
    if ($file['error'] !== UPLOAD_ERR_OK) return null;
    if (!in_array($file['type'], $allowedMimes, true)) return null;
    if ($file['size'] > 5 * 1024 * 1024) return null; // 5MB
    
    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = bin2hex(random_bytes(16)) . '.' . $ext;
    $destination = $uploadDir . '/' . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $destination)) {
        return $filename;
    }
    return null;
}
?>

8. JSON API 回應標準化

<?php
function jsonResponse(array $data = [], int $status = 200, string $message = ''): never {
    http_response_code($status);
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode([
        'success' => $status < 400,
        'message' => $message,
        'data' => $data,
        'timestamp' => time(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

// 用法
jsonResponse(['user' => $user], 200, '登入成功');
jsonResponse([], 422, '驗證失敗');
?>

9. 簡易快取封裝 (檔案/Redis 切換)

<?php
interface CacheDriver {
    public function get(string $key);
    public function set(string $key, $value, int $ttl): bool;
    public function delete(string $key): bool;
}

class FileCache implements CacheDriver {
    private string $dir;
    public function __construct(string $dir) { $this->dir = $dir; }
    public function get(string $key) {
        $file = $this->dir . '/' . md5($key) . '.cache';
        if (!is_file($file) || time() - filemtime($file) > 3600) return null;
        return unserialize(file_get_contents($file));
    }
    public function set(string $key, $value, int $ttl): bool {
        return file_put_contents($this->dir . '/' . md5($key) . '.cache', serialize($value)) !== false;
    }
    public function delete(string $key): bool {
        return @unlink($this->dir . '/' . md5($key) . '.cache');
    }
}
?>

10. 命令列腳本標準結構

<?php
#!/usr/bin/env php
<?php
// cli.php
if (php_sapi_name() !== 'cli') { die('CLI only'); }

$args = $argv;
array_shift($args); // 移除腳本名稱

$commands = [
    'migrate' => fn() => migrateDatabase(),
    'seed' => fn() => seedData(),
    'clean' => fn() => cleanCache(),
];

$cmd = $args[0] ?? 'help';
if (isset($commands[$cmd])) {
    $commands[$cmd]();
} else {
    echo "Usage: php cli.php [migrate|seed|clean]\n";
}
?>

內化這些模式,日常開發事半功倍,程式碼品質穩步提升。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved