PHP速查表



這份PHP速查表提供了一個對所有PHP程式設計概念的快速概述和複習,對學生和開發者都很有幫助。如果您正在準備任何考試或面試,我們建議您通讀這份速查表,以學習和提升您的PHP技能。

指令碼語法

使用以下語法編寫PHP指令碼:

<?php
   // Your PHP code here
?>

您也可以使用簡短的echo標籤:

<?= "Hello, World!" ?>

列印"Hello, World!"

您可以使用PHP的**echo**語句列印"Hello, World!"

<?php
   echo "Hello, World!";
?>

註釋

PHP提供單行和多行註釋。單行註釋以**#**或**//**開頭,多行註釋用**/***和***/**括起來。

1. 單行註釋

// Write single-line comment here
# Write single-line comment here

2. 多行註釋

/* You can write
multi-line comment like this*/

變數

PHP變數儲存資料和資訊。變數可以使用美元符號 ($) 後跟變數名來宣告。

<?php
   $age = 21;
   $name = "Kelly Hu";
?>

列印變數

您可以使用PHP echo語句來列印變數。

<?php
   $age = 21;
   $name = "Kelly Hu";
   echo "My name is $name";
   echo "<br>";
   echo "I am $age years old.";
?>

列印換行符

您可以使用echo語句和"\n"來在PHP中列印換行符。要在瀏覽器中顯示換行符,請使用"<br />"標籤。

1. 在控制檯中列印

<?php
   echo "Hello, World!\n";
   echo "This is on a new line.\n";
?>

2. 在Web瀏覽器中列印

<?php
   echo "Hello, World!<br>";
   echo "This is on a new line.<br>";
?>

列印文字

您可以使用以下函式列印文字:

  • echo
  • print
  • printf
  • print_r

1. 使用echo列印

使用**echo**列印一個或多個字串。

<?php
   echo "Hello, World!", " Hello PHP";
   $a = 10;
   $b = "Okay";
   echo "\nValue of a is $a and value of b is $b";
?>

2. 使用print列印

使用**print**列印單個字串。

<?php
   print "Hello, World!";
?>

3. 使用printf列印

使用**printf**列印格式化字串。

<?php
   printf("Hello, %s!", "World");
?>

4. 使用print_r列印

使用print_r進行除錯,顯示變數(特別是陣列或物件)的人類可讀資訊。

<?php
   $arr = array('Hyderabad', 'Bangalore', 'Mangalore');
   print_r($arr);
?>

將HTML元素與文字嵌入

您可以使用echo和print函式將HTML元素與文字嵌入。

<?php
   echo "<h1>Hello, World!</h1>";
   echo "<p>This is a paragraph.</p>";
?>

在HTML中嵌入PHP

您也可以在HTML元素內嵌入PHP。

<html>
<body>
   <h1><?php echo "Welcome to My Website!"; ?></h1>
   <p><?php echo "This is a dynamic paragraph."; ?></p>
</body>
</html>

將PHP變數與HTML組合

您可以按如下方式在HTML元素中包含PHP變數:

<?php
   $name = "Kelly Hu";
   echo "<p>Hello, <em>$name</em>! Welcome to TutorialsPoint.</p>";
?>

資料型別

1. 字串

字串資料型別表示一系列字元。

$str1 = "Hello, World!";
$str2 = 'PHP Data Types';

2. 整數

整數資料型別表示介於-2,147,483,648和2,147,483,647之間的非十進位制數(在32位系統上)。

$int = 42;

3. 浮點數(雙精度浮點數)

浮點數(雙精度浮點數)資料型別表示帶有小數部分的數字。

$float = 3.14;

4. 布林值

布林資料型別表示兩個可能的值:TRUE或FALSE。

$is_admin = true;
$is_guest = false;

5. 陣列

PHP陣列型別在一個變數中儲存多個值。

// Indexed array
$cities = array("Hyderabad", "Bangalore", "Mangalore");
// Associative array
$person = array("name" => "Kelly Hu", "age" => 22);

6. 物件

陣列型別是類的例項。

<?php
   class Person {
      public $name;
      public function __construct($name) {
         $this->name = $name;
      }
      public function getName() {
         return $this->name;
      }
   }
   $p = new Person("Kelly Hu");
   echo $p->getName();  // Outputs: Kelly Hu
?>

7. NULL

NULL型別表示沒有值的變數。

$var = null;

字串

PHP字串是由單引號('Hello')或雙引號("Hello")括起來的一系列字元。

1. 建立和列印字串

您可以透過將字串賦給變數來建立字串變數,並使用echo語句列印它。

<?php
   $str = "Kelly Hu";
   echo "Hello, $str!";
?>

2. 字串連線

可以使用點 (.) 運算子連線兩個字串。

<?php
   $str = "Hello" . " " . "World!";
   echo $str;
?>

3. 字串長度

您可以使用strlen()方法獲取字串長度。

$len = strlen("Hello");  // Output: 5

4. 字串函式

一些常用的字串函式用於各種字串操作,如下所示:

函式名稱 用途 示例
strlen() 返回字串的長度。
$str = "Hello World!";
echo strlen($str);
str_word_count() 返回字串中單詞的數量。
$str = "Hello World!";
echo str_word_count($str);
strrev() 返回反轉後的字串。
$str = "Hello";
echo strrev($str);
strpos() 返回子字串第一次出現的索引。
$str = "Hello World!";
echo strpos($str, "World");
str_replace() 將字串中的某些字元替換為其他字元。
$str = "Hello World!";
echo str_replace("World", "Harry", $str);
strtolower() 返回轉換為小寫的字串。
$str = "HELLO WORLD!";
echo strtolower($str);
strtoupper() 返回轉換為大寫的字串。
$str = "hello world!";
echo strtoupper($str);
trim() 移除兩端的多餘空格或預定義字元。
$str = " Hello World! ";
echo trim($str);
ltrim() 移除左側的多餘空格或預定義字元。
$str = " Hello World! ";
echo ltrim($str);
rtrim() 移除右側的多餘空格或預定義字元。
$str = " Hello World! ";
echo rtrim($str);
str_repeat() 將字串重複指定次數。
$str = "Hi! ";
echo str_repeat($str, 3);
substr() 返回字串的一部分。
$str = "Hello World!";
echo substr($str, 6, 5);
ucfirst() 返回將字串首字母轉換為大寫的字串。
$str = "hello world!";
echo ucfirst($str);
ucwords() 返回將字串中每個單詞的首字母轉換為大寫的字串。
$str = "hello world!";
echo ucwords($str);
strcmp() 比較兩個字串(區分大小寫)。
$str1 = "Hello";
$str2 = "hello"; echo strcmp($str1, $str2);
strcasecmp() 比較兩個字串(不區分大小寫)。
$str1 = "Hello";
$str2 = "hello"; echo strcasecmp($str1, $str2);
str_shuffle() 隨機打亂字串的字元順序。
$str = "Hello";
echo str_shuffle($str);
number_format() 格式化數字,以千位分隔符分組。
$num = 1234567.89;
echo number_format($num, 2);

您可以訪問我們的參考頁面瞭解更多關於這些方法的資訊:PHP 字串函式參考

跳脫字元

PHP 支援以下跳脫字元:

跳脫字元 描述
\\ 反斜槓
\' 單引號
\" 雙引號
\n 換行
\r 回車
\t 水平製表符
\b 退格
\f 換頁
\v 垂直製表符
\0 空字元
\xHH 十六進位制值(HH 為十六進位制程式碼)
\u{HHHH} Unicode 字元 (PHP 7.2+)

跳脫字元示例

<?php
   echo "Hello\nWorld";
   echo "Hello\tWorld.\n";
   echo "This is single quote: It\'s Me.\n";
   echo "This is double quote: \"Hello, World!\"\n";
   echo "This is a backslash: \\\n";
?>

運算子

PHP 運算子 是用於對變數和值執行運算的符號。以下是不同型別的運算子:

所有運算子列表

運算子型別 運算子 描述 示例
算術運算子 + 加法 5 + 3(輸出 8)
- 減法 5 - 3(輸出 2)
* 乘法 5 * 3(輸出 15)
/ 除法 5 / 2(輸出 2.5)
% 取模(餘數) 5 % 2(輸出 1)
賦值運算子 = 賦值 $x = 5;
+= 加法賦值 $x += 3;(等同於 $x = $x + 3;)
-= 減法賦值 $x -= 2;(等同於 $x = $x - 2;)
*= 乘法賦值 $x *= 2;(等同於 $x = $x * 2;)
/= 除法賦值 $x /= 2;(等同於 $x = $x / 2;)
%= 取模賦值 $x %= 3;(等同於 $x = $x % 3;)
比較運算子 == 等於(值) ($x == $y)
=== 全等(值和型別) ($x === $y)
!= 不等於 ($x != $y)
!== 不全等(值或型別) ($x !== $y)
< 小於 ($x < $y)
> 大於 ($x > $y)
<= 小於等於 ($x <= $y)
>= 大於等於 ($x >= $y)
邏輯運算子 && 邏輯與 ($x && $y)
|| 邏輯或 ($x || $y)
! 邏輯非 !$x
字串運算子 . 連線(連線兩個字串) $str = "Hello" . " World";
增量/減量運算子 ++ 增量(加一) ++$x 或 $x++
-- 減量(減一) --$x 或 $x--

PHP 運算子示例

<?php
   // Arithmetic Operators
   $a = 10;
   $b = 3;
   echo $a + $b;
   echo $a % $b;

   // Assignment Operators
   $x = 5;
   $x += 2;
   echo $x;

   // Comparison Operators
   var_dump($x == 7);

   // Logical Operators
   if ($x > 5 && $x < 10) {
      echo "x is between 5 and 10.";
   }

   // String Operator
   $greeting = "Hello, " . "World!";
   echo $greeting;

   // Increment/Decrement Operators
   echo ++$x;
   echo $x--;
?>

條件語句

PHP 條件語句用於根據條件執行程式碼。條件語句包括:

  • if
  • if else
  • 多重 if else
  • 巢狀 if else
  • switch

1. if 語句

<?php
   $x = 10;
   if ($x > 5) {
      echo "x is greater than 5";
   }
?>

2. if else 語句

<?php
   $x = 3;
   if ($x > 5) {
      echo "x is greater than 5";
   } else {
      echo "x is not greater than 5";
   }
?>

3. 多重 if else 語句

<?php
   $x = 10;
   if ($x > 10) {
      echo "x is greater than 10";
   } elseif ($x == 10) {
      echo "x is equal to 10";
   } else {
      echo "x is less than 10";
   }
?>

4. 巢狀 if else 語句

<?php
   $x = 10;
   if ($x > 10) {
      echo "x is greater than 10";
   } elseif ($x == 10) {
      echo "x is equal to 10";
   } else {
      echo "x is less than 10";
   }
?>

5. switch 語句

<?php
   $day = 3;
   switch ($day) {
      case 1:
         echo "Monday";
         break;
      case 2:
         echo "Tuesday";
         break;
      case 3:
         echo "Wednesday";
         break;
      case 4:
         echo "Thursday";
         break;
      case 5:
         echo "Friday";
         break;
      case 6:
         echo "Saturday";
         break;
      case 7:
         echo "Sunday";
         break;
      default:
      echo "Invalid day";
   }
?>

數學函式

PHP 數學函式用於執行各種數學運算。以下是數學函式:

函式 示例
abs() echo abs(-5); // 輸出:5
ceil() echo ceil(4.3); // 輸出:5
floor() echo floor(4.7); // 輸出:4
round() echo round(4.5); // 輸出:5
max() echo max(1, 3, 2); // 輸出:3
min() echo min(1, 3, 2); // 輸出:1
pow() echo pow(2, 3); // 輸出:8
sqrt() echo sqrt(16); // 輸出:4
rand() echo rand(1, 100); // 輸出:隨機數
mt_rand() echo mt_rand(1, 100); // 輸出:隨機數
sin() echo sin(deg2rad(90)); // 輸出:1
cos() echo cos(deg2rad(180)); // 輸出:-1
tan() echo tan(deg2rad(45)); // 輸出:1
deg2rad() echo deg2rad(180); // 輸出:3.14159
rad2deg() echo rad2deg(M_PI); // 輸出:180

常量

PHP 常量 是具有固定值的變數。常量使用 **define()** 定義。

<?php
   define("SITE_NAME", "MyWebsite");
   echo SITE_NAME;
?>

魔術常量

PHP 魔術常量 是具有特殊含義的特殊常量。以下是魔術常量:

常量名稱 描述
__LINE__ 檔案的當前行號。
__FILE__ 檔案的完整路徑和檔名。
__DIR__ 檔案的目錄。
__FUNCTION__ 函式的名稱(區分大小寫)。
__CLASS__ 類的名稱(區分大小寫)。
__METHOD__ 方法的名稱(區分大小寫)。
__NAMESPACE__ 當前名稱空間(如果沒有則為空)。
__TRAIT__ 特性的名稱(區分大小寫)。

魔術常量示例

<?php
   echo "Current line: " . __LINE__ . "<\n";
   echo "Full file path: " . __FILE__ . "<\n";
   echo "Directory: " . __DIR__ . "<\n";

   function tpFunction() {
      echo "Function name: " . __FUNCTION__ . "<\n";
   }

   class tpClass {
      public function tpFun() {
         echo "Method name: " . __METHOD__ . "<\n";
      }
   }

   namespace MyNamespace;
   echo "Namespace: " . __NAMESPACE__ . "<\n";
?>

迴圈

PHP 迴圈 多次重複執行一段程式碼。以下是迴圈的型別:

  • for
  • foreach
  • while
  • do...while

1. for 迴圈

<?php
   echo "The for Loop:<\n";
   for ($i = 0; $i < 10; $i++) {
      echo "Iteration: $i<\n";
   }
?>

2. foreach 迴圈

<?php
   echo "The foreach Loop:<\n";
   $cities = ['Hyderabad', 'Bangalore', 'Mangalore'];
   foreach ($cities as $city) {
      echo "City: $city<\n";
   }
?>

3. while 迴圈

<?php
   echo "The while Loop:<\n";
   $count = 0;
   while ($count < 10) {
      echo "Count: $count<\n";
      $count++;
   }
?>

4. do...while 迴圈

<?php
   echo "The do...while Loop:<\n";
   $count = 0;
   do {
      echo "Count: $count<\n";
      $count++;
   } while ($count < 10);
?>

函式

PHP 函式 是可以按需執行的程式碼塊。以下是一個簡單的函式示例:

<?php
   // Defining function
   function printName($name) {
      return "Hello, " . $name . "!";
   }

   // Calling function
   echo printName("Kelly Hu");
?>

陣列

PHP 陣列 用於儲存多個相同或不同型別的值。以下是不同型別的陣列:

  • 索引陣列
  • 關聯陣列
  • 多維陣列

1. 索引陣列

<?php
   $cities = ["Hyderabad", "Bangalore", "Mangalore"];

   // Accessing elements
   echo $cities[0];
   echo $cities[1];
   echo $cities[2];
?>

2. 關聯陣列

<?php
   // Associative array with named keys
   $student = [
      "name" => "Kelly Hu",
      "age" => 21,
      "city" => "Brentwood"
   ];

   // Accessing elements by key
   echo $student["name"];
   echo $student["age"];
   echo $student["city"];
?>

全域性變數 - 超全域性變數

PHP 全域性變數 (也稱為超全域性變數)是內建的全域性陣列,用於提供資訊或跟蹤變數。超全域性變數包括:

超全域性變數 描述
$_GET 收集透過 GET 請求中的 URL 引數傳送的資料。
$_POST 收集透過 HTTP POST 方法傳送的資料。
$_REQUEST 收集來自 $_GET$_POST$_COOKIE 的資料。
$_SESSION 為單個使用者跨頁面儲存資料。
$_COOKIE 將資料作為小型文字檔案儲存在客戶端的瀏覽器中。
$_FILES 管理檔案上傳。
$_ENV 儲存環境變數。
$_SERVER 包含有關伺服器和執行環境的資訊。
$_GLOBALS 訪問 PHP 指令碼中的所有全域性變數。

正則表示式

PHP 正則表示式是用於匹配字串的模式。

1. 驗證電子郵件地址

<?php
   $email = "myemail@domain.com";
   if (preg_match("/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/", $email)) {
      echo "Valid Email.";
   } else {
      echo "Invalid Email";
   }
?>

2. 驗證電話號碼

<?php
   $phone = "1234567890";
   if (preg_match("/^\d{10}$/", $phone)) {
      echo "It's a valid phone number.";
   } else {
      echo "It's not a valid phone number.";
   }
?>

3. 驗證 URL

<?php
   $url = "https://tutorialspoint.tw";
   if (preg_match("/\b(?:https?|ftp):\/\/[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}\b/", $url)) {
      echo "It's a valid URL";
   } else {
      echo "It's not a valid URL";
   }
?>

表單處理

PHP 表單處理是關於透過 HTML 表單收集和驗證使用者資料。這是一個示例:

<form method="post" action="form.php">
   Name: <input type="text" name="name">
   <input type="submit" value="Submit">
</form>

<?php
   // Check if form was submitted or not
   if ($_SERVER["REQUEST_METHOD"] == "POST") {
      $name = htmlspecialchars($_POST['name']);
      if (!empty($name)) {
         echo "Hello, " . $name . "!";
      } else {
         echo "Fill your name.";
      }
   }
?>

日期和時間

使用 **date()** 函式獲取日期和時間。這是一個示例:

<?php
   // Get the current date and time
   echo "Current Date: " . date("Y-m-d") . "<\n";
   echo "Current Time: " . date("H:i:s") . "<\n";
   echo "Full Date and Time: " . date("Y-m-d H:i:s");
?>

包含檔案

使用 include 語句 在另一個 PHP 檔案中包含檔案。

include 'header.php';

檔案處理

PHP 檔案處理 用於建立、讀取、寫入和管理檔案。

1. 開啟和關閉檔案

<?php
   $file = fopen("file1.txt", "w");
   fclose($file);
?>

2. 寫入檔案

<?php
   $file = fopen("file1.txt", "w");
   fwrite($file, "Some text to file.");
   fclose($file);
?>

3. 從檔案中讀取

<?php
   $file = fopen("file1.txt", "r");
   $content = fread($file, filesize("file1.txt"));
   echo $content;
   fclose($file);
?>

4. 附加到檔案

<?php
   $file = fopen("file1.txt", "a");
   fwrite($file, "\nSome extra text.");
   fclose($file);
?>

5. 刪除檔案

<?php
   if (file_exists("file1.txt")) {
      unlink("file1.txt");
      echo "DONE.";
   } else {
      echo "File doesn't exist";
   }
?>

檔案上傳

PHP 檔案上傳 允許您將檔案上傳到伺服器。

move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/" . $_FILES["file"]["name"]);

Cookie

PHP Cookie 在客戶端計算機上儲存少量資料。

setcookie("user", "Kelly Hu", time() + (86400 * 30), "/");

會話

PHP 會話 為使用者跨多個頁面儲存資料。

session_start();
$_SESSION["username"] = "Kelly Hu";

過濾器

PHP 過濾器用於驗證和清理資料。

$email = filter_var($email, FILTER_VALIDATE_EMAIL);
廣告