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


当前回答

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

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

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

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

其他回答

Use:

$intValue = 1;
$string = sprintf('%d', $intValue);

也可能是:

$string = (string)$intValue;

Or:

settype($intValue, 'string');

我想说这取决于上下文。可以使用Strval()或强制转换操作符(string)。然而,在大多数情况下,PHP将决定什么对你来说是好的,例如,你使用echo或printf…

注意:die()需要一个字符串,不会显示任何int:)

可以使用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";

我尝试了上面所有的方法,但当我在另一个字符串中嵌入值时,我得到了“数组到字符串转换”错误。如果你有同样的问题,试试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。