<?php
// 輸出語句
echo 'Hello', 'World'; // 多參數、無回傳值、速度較快
print 'Hello World'; // 單參數、回傳 1、可用於複雜表達式
// 註解風格
# Shell 風格單行註解
// C++ 風格單行註解
/* 多行註解
可跨行 */
?>
<?php
// 變數:$ 開頭、區分大小寫、首字母或底線
$name = 'PHP';
$_age = 28;
$UserName = 'Admin'; // 駝峰式
// 常數:慣用全大寫、無 $ 符號、全域可見
define('APP_VERSION', '1.0.0');
define('DEBUG_MODE', true);
echo APP_VERSION; // 1.0.0
// 預定義常數
echo PHP_VERSION; // 8.3.0
echo PHP_OS; // Linux
?>
| 操作 | 語法 | 說明 |
|---|---|---|
| 連接 | $a . $b | 點號運算子 |
| 雙引號解析 | "Hello $name" | 變數內插、支援跳脫序列 |
| 單引號字面 | 'Hello $name' | 不解析變數、速度略快 |
| Heredoc | <<<EOT ... EOT; | 多行字串、類似雙引號行為 |
| Nowdoc | <<<'EOT' ... EOT; | 多行字串、類似單引號行為 |
<form action="handle.php" method="POST">
<label>姓名:<input type="text" name="name" required></label>
<label>Email:<input type="email" name="email"></label>
<label>性別:
<input type="radio" name="gender" value="M">男
<input type="radio" name="gender" value="F">女
</label>
<label>興趣:
<input type="checkbox" name="interests[]" value="Music">音樂
<input type="checkbox" name="interests[]" value="Movie">電影
</label>
<button type="submit">送出</button>
</form>
<?php
// 取得資料(過濾輸入)
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$gender = $_POST['gender'] ?? null;
$interests = $_POST['interests'] ?? [];
// 驗證
$errors = [];
if (!$name) $errors[] = '姓名必填';
if (!$email) $errors[] = 'Email 格式錯誤';
if ($errors) {
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
exit;
}
// 處理核選陣列
$interestStr = implode(', ', $interests);
// 輸出結果
echo "<p>感謝 $name,您的興趣:$interestStr</p>";
?>
$_GET:URL 參數 ?id=1$_POST:POST 表單資料$_REQUEST:合併 GET/POST/COOKIE(不建議直接使用,來源不明確)$_SESSION:會話資料(需 session_start())$_COOKIE:Cookie 資料$_SERVER:伺服器環境變數$_FILES:上傳檔案資訊$_ENV:環境變數<?php
// 建立
$indexed = ['Apple', 'Banana', 'Cherry']; // 索引陣列
$assoc = ['name' => 'John', 'age' => 30]; // 關聯陣列
$multi = [['id'=>1, 'name'=> 'A'], ['id'=>2, 'name'=> 'B']]; // 多維
// 遍歷
foreach ($assoc as $key => $value) { ... }
foreach ($multi as $row) { echo $row['name']; }
// 常用函數
count($arr); // 元素個數
array_push($arr, $v); // 尾部推入
array_pop($arr); // 尾部彈出
array_unshift($arr,$v); // 頭部推入
array_shift($arr); // 頭部彈出
in_array($v, $arr); // 檢查值存在
array_key_exists($k,$arr); // 檢查鍵存在
array_merge($a, $b); // 合併陣列
array_map('strtoupper', $arr); // 映射處理
array_filter($arr, fn($v)=>$v>10); // 過濾
?>
<?php
// 條件判斷
if ($score >= 90) { $grade = 'A'; }
elseif ($score >= 80) { $grade = 'B'; }
else { $grade = 'C'; }
// 三元運算子
$status = $age >= 18 ? '成年' : '未成年';
// Switch
switch ($day) {
case 0: case 6: echo '週末'; break;
default: echo '平日';
}
// 迴圈
for ($i=0; $i<10; $i++) { ... }
while ($row = $stmt->fetch()) { ... }
foreach ($items as $item) { ... }
?>
PHP 5.4 起移除 magic_quotes_gpc。現代做法:
htmlspecialchars()json_encode()escapeshellarg()