1

在下面我尝试$code = (string)$code;没有成功,如何在 PHP 中将数字转换为字符串?

$code = 087326487326;
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
  print substr($code, 0, $i)."<br/>";
}

输出:

1
0

$code = '087326487326';
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
  print substr($code, 0, $i)."<br/>";
}

输出:

12
087326487326
08732648732
0873264873
087326487
08732648
0873264
087326
08732
0873
087
08
0
4

4 回答 4

7

It's failing because it's prefixed with a 0, making PHP attempt to interpret it as an octal number, where 8 is not a valid octal digit as it parses the string, so you get 0.

The solution is to use a (string) cast or strval(), but you need to remove the leading zero from your definition of $code.

$code = 87326487326;
var_dump( $code, (string) $code, strval( $code));

This will output (on an x64 machine):

int(87326487326) string(11) "87326487326" string(11) "87326487326" 
于 2012-07-15T15:02:16.153 回答
1

I Like this type juggling way, if you have.

$code = 087326487326;

All you have to do to cast it to string is:

$code = "$code";

EDIT

Sorry, was a bit distracted, I tested it wrong. What was said above is true, leading zero's are a disaster. Way not remove it, and pad the number later?

于 2012-07-15T15:05:45.820 回答
1

您可以使用以下函数转换为字符串:

strval($code);
于 2021-08-09T10:10:41.267 回答
0

你可以像这样使用类型转换吗

 $code = (string)58963245874;

检查它你打印它的类型如下

 echo gettype($code);
于 2017-03-31T13:34:09.867 回答