In the following I tried $code = (string)$code;
with no success, how can I convert number to string in PHP?
$code = 087326487326;
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
print substr($code, 0, $i)."<br/>";
}
Output:
1
0
and
$code = '087326487326';
$strlen = strlen($code);
print $strlen."<br/>";
for ($i = $strlen; $i >= 0; $i--) {
print substr($code, 0, $i)."<br/>";
}
Output:
12
087326487326
08732648732
0873264873
087326487
08732648
0873264
087326
08732
0873
087
08
0
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"
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?
may you could be use type cast like this
$code = (string)58963245874;
for check it you print its type like below
echo gettype($code);