這些題目看似簡單,卻能快速考察候選人的語法熟練度、邏輯思維與 API 掌握度。整理高頻考點,附最佳寫法解析。
考點: 三元運算符嵌套、邏輯簡潔性。
function getMax($a, $b, $c) {
return ($a > $b) ? (($a > $c) ? $a : $c) : (($b > $c) ? $b : $c);
}
// 測試
echo getMax(3, 9, 6); // 9
// 現代寫法 (PHP 7.0+): 更優雅
function getMaxModern(...$nums) {
return max($nums); // 內建函數最優
}
考點: strtotime 相對時間解析、date 格式化、時區設置。
date_default_timezone_set('PRC'); // 必須先設置時區,否則默認 UTC
echo date('Y年m月d日 H:i:s', strtotime('-1 day'));
// 輸出示例: 2024年05月20日 14:30:00
// strtotime 更多相對時間技巧
strtotime('+1 week 3 days 7 hours 5 seconds'); // 組合運算
strtotime('next Monday'); // 下周一
strtotime('last Monday'); // 上周一
strtotime('first day of this month'); // 本月 1 號
strtotime('last day of February 2024'); // 2 月最後一天 (自動處理閏年)
$str = " \t\n Hello World \r\n "; echo trim($str); // "Hello World" // ltrim/rtrim 單側去除
$arr = [1, 2, 2, 3, 3, 3]; $unique = array_values(array_unique($arr)); // [1, 2, 3] // array_unique 保留鍵名,array_values 重置為 0 起始索引
$vars = [0, '0', '', null, false, [], 'false'];
foreach ($vars as $v) {
var_dump(empty($v)); // 0, '0', '', null, false, [] 均為 true
// 注意: 'false' 字符串為 false
}
// 不推薦: $_GET['id'] 可能觸發 Undefined index // 推薦: $id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT); // 同時驗證類型 $name = $_GET['name'] ?? 'guest'; // PHP 7.0+ Null 合並運算符
// 方案: 日期時間 + 微秒 + 隨機數 + 業務前綴
function genOrderNo($prefix = 'ORD') {
return sprintf('%s%s%04d', $prefix, date('YmdHis'), random_int(1000, 9999));
// 生產環境建議引入 Redis 原子計數器或 Snowflake 算法
}
備考心法: 熟練掌握 array_*、str_*、date、filter 系列函數,理解類型轉換規則,代碼簡潔、健壯、利用內建函數是加分項。