在PHP中有方法将整数转换为字符串吗?
当前回答
可以使用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";
其他回答
$foo = 5;
$foo = $foo . "";
现在$foo是一个字符串。
但是,你可能需要习惯选角。因为铸造是完成这类事情的正确方式:
$foo = 5;
$foo = (string)$foo;
另一种方法是用引号封装:
$foo = 5;
$foo = "$foo"
Use:
$intValue = 1;
$string = sprintf('%d', $intValue);
也可能是:
$string = (string)$intValue;
Or:
settype($intValue, 'string');
有很多方法可以做到这一点。
两个例子:
$str = (string) $int;
$str = "$int";
有关更多信息,请参阅PHP类型杂耍手册。
我尝试了上面所有的方法,但当我在另一个字符串中嵌入值时,我得到了“数组到字符串转换”错误。如果你有同样的问题,试试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。
推荐文章
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- PHP中的echo, print和print_r有什么区别?
- 如何删除表中特定列的第一个字符?
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- 将整数转换为字符串,以逗号表示千
- 如何将XML转换成PHP数组?
- 将JavaScript字符串中的多个空格替换为单个空格
- 如何将对象转换为数组?
- printf()和puts()在C语言中的区别是什么?
- 从IP地址获取位置
- TypeScript枚举对象数组
- jQuery -替换字符串中某个字符的所有实例