HOWTO · PHP

如何在 PHP 中將整數轉換為字串

本文介紹如何在 PHP 中將整數轉換為字串。

本頁內容

PHP 提供多種將整數轉換為字串的方法。最直接的做法是顯式的 (string) 強制轉換,內建函式 strval() 也能完成同樣的工作。此外,在任何 PHP 預期收到字串的地方,整數都會被隱式轉換——例如在雙引號字串中,或使用串接運算子連接值時——因此插值與串接都不需要另外呼叫轉換。以下逐一示範各種方法,並在最後說明該優先採用哪一種。

使用 (string) 強制轉換將整數轉換為字串

強制轉換會直接在程式碼中標明目標型別。把 (string) 放在整數常值或存放整數的變數前面,PHP 就會回傳其字串表示形式,可立即儲存或傳遞到任何需要字串的地方。

執行以下範例:

本節中的程式碼以及顯示的標籤或輸出仍為英文。

<?php
$variable = 10;
$string1 = (string)$variable;
echo "The variable is converted to a string and its value is $string1.\n";
?>
The variable is converted to a string and its value is 10.

由於轉換是顯式進行的,意圖一目瞭然,且結果確實是 string——可用 gettype($string1) 或 var_dump() 確認。當你需要的是真正的字串值而非僅是印出的文字時,(string) 是最符合 PHP 慣用寫法的選擇。

使用 strval() 將整數轉換為字串

strval() 是 PHP 內建、用來把值轉換成字串的函式。將變數作為參數傳入——strval($variable)——它就會回傳字串形式;對整數而言,結果與 (string) 強制轉換產生的數字完全相同。

本節中的程式碼以及顯示的標籤或輸出仍為英文。

<?php
$variable = 10;
$string1 = strval($variable);
echo "The variable is converted to a string and its value is $string1.\n";
?>
The variable is converted to a string and its value is 10.
警告
函式 strval() 不能用於陣列或物件;若傳入這類值,函式會回傳傳入參數的型別名稱。

在雙引號字串中將整數轉換為字串

PHP 會解析嵌入雙引號字串中的變數並代換其值——這項功能稱為變數插值(variable interpolation)。當變數存放整數時,PHP 會自動將其轉為字串,因此不需要顯式轉換。

本節中的程式碼以及顯示的標籤或輸出仍為英文。

<?php
$variable = 10;
echo "The variable is converted to a string and its value is $variable.\n";
?>
The variable is converted to a string and its value is 10.

插值只在雙引號字串(以及 heredoc 區塊)中有效:單引號內的 '$variable' 會被視為常值文字,印出的是 $variable 而非 10。若要保留轉換後的值而不只是印出來,請指派插值後的字串——$string1 = "$variable"; 會得到與強制轉換相同的 "10"。

使用字串串接將整數轉換為字串

. 運算子用來連接字串,而 PHP 的型別協調(type juggling)會替你轉換整數運算元,因此串接也是一條隱式轉換途徑。PHP 字串串接一文對此運算子有更深入的介紹。

本節中的程式碼以及顯示的標籤或輸出仍為英文。

<?php
$variable = 10;
$string1 = "The variable is converted to a string and its value is ".$variable.".";
echo $string1."\n";
?>
The variable is converted to a string and its value is 10.

若只需要轉換,可將整數與 ""——一個不含任何字元的字串——串接,放在整數的任一側都可以。"".$variable 與 $variable."" 都會得到 "10":

<?php
$variable = 10;
echo "".$variable."\n";
echo $variable.""."\n";
?>
10
10

選擇適當的轉換方法

當你需要真正的字串值——用來儲存、傳給預期字串的函式或 API、或留待之後重複使用——請使用 (string) 強制轉換或 strval()。兩者都讓轉換明確可見;強制轉換是較慣用、速度也略快的寫法,而當你的程式碼本就以函式呼叫為主時,strval() 讀起來較自然。如果只想把整數嵌入較大的輸出中,兩者都可省略:插值與 . 串接本來就會直接產生字串,額外增加轉換步驟毫無意義。請記住各自的限制——插值僅適用於雙引號字串,strval() 不接受陣列與物件——若需要格式化結果,sprintf("%d", $variable) 這類函式能對最終文字提供最精細的控制。