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


当前回答

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

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

其他回答

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

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

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

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

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

$foo = 5;

$foo = $foo . "";

现在$foo是一个字符串。

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

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

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

$foo = 5;
$foo = "$foo"
$integer = 93;
$stringedInt = $integer.'';

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