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


当前回答

有许多可能的转换方式:

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

其他回答

这里的答案很好地证明了,是的,有几种方法。然而,在PHP中,实际上很少需要这样做。编写PHP的“教条方式”是依赖于该语言的松散类型系统,该系统将根据需要透明地强制输入类型。对于整数值,这通常没有问题。但是,使用浮点值时应该非常小心。

我的情况:

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

我在工作……

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

$foo = 5;

$foo = $foo . "";

现在$foo是一个字符串。

但是,你可能需要习惯选角。因为铸造是完成这类事情的正确方式:

$foo = 5;
$foo = (string)$foo;

另一种方法是用引号封装:

$foo = 5;
$foo = "$foo"

我尝试了上面所有的方法,但当我在另一个字符串中嵌入值时,我得到了“数组到字符串转换”错误。如果你有同样的问题,试试implode()函数。 例子:

$integer = 0;    
$id = implode($integer);    
$text = "Your user ID is: ".$id ;
$amount = 2351.25;
$str_amount = "2351.25";

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

echo将返回string。