在PHP中有方法将整数转换为字符串吗?


当前回答

我的情况:

echo strval("12"); => 12
echo strval("0"); => "0"

我在工作……

$a = "12";
$b = "0";
echo $a * 1; => 12
echo $b * 1; => 0

其他回答

你可以使用句号操作符并将一个字符串连接到它(它将被类型转换为字符串):

$integer = 93;
$stringedInt = $integer . "";

或者,更准确地说,你可以直接将整数类型转换为字符串:

$integer = 93;
$stringedInt = (string) $integer;
$integer = 93;
$stringedInt = $integer.'';

$integer = 93;
$stringedInt = $integer."";

可以使用strval()函数将数字转换为字符串。

从维护的角度来看,您正在尝试做什么是显而易见的,而不是其他一些更深奥的答案。当然,这取决于你所处的环境。

$var = 5;

// Inline variable parsing
echo "I'd like {$var} waffles"; // = I'd like 5 waffles

// String concatenation 
echo "I'd like ".$var." waffles"; // I'd like 5 waffles

// The two examples above have the same end value...
// ... And so do the two below

// Explicit cast 
$items = (string)$var; // $items === "5";

// Function call
$items = strval($var); // $items === "5";
$amount = 2351.25;
$str_amount = "2351.25";

$strCorrectAmount = "$amount";
echo gettype($strCorrectAmount);    //string

echo将返回string。

有许多可能的转换方式:

$input => 123
sprintf('%d',$input) => 123
(string)$input => 123
strval($input) => 123
settype($input, "string") => 123