开发者

PHP cast to integer with only 1 or 2 chars

How can I cast to integer in PHP using only 1 or two chars?

If I have the operation $a = (int) $b; it will result using those two (or one) chars:

$a = <*insert the needed 1 or开发者_JAVA百科 2 chars*> $b;

I need only to cast to integer. Thank you.


Prefix a + (the unary plus):

$a=+$b

A pretty common trick for code-golfing that also works in PowerShell and other languages.

$ php -r "var_dump('4');"
string(1) "4"
$ php -r "var_dump(+'4');"
int(4)


$a = sprintf("%02d", $b);

If you need to pad it with something other than zero, replace the zero with the character you need.


You can make a function, I guess. Of other type of shorter cast I'm unaware.

function z($i)
{
return (int)$i;
}

$a = z($b);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜