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


当前回答

$integer = 93;
$stringedInt = $integer.'';

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

其他回答

我想说这取决于上下文。可以使用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";

有许多可能的转换方式:

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

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

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

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

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

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