【问题标题】:Comparing two integers in php比较php中的两个整数
【发布时间】:2016-09-21 10:34:50
【问题描述】:

我需要在 PHP 中比较两个整数。我有这个例子:

$a=00713132161838;
$b=713132161838;

我怎样才能使这种比较为真?我需要从 $a 中删除前导零。

我使用了 number_format 函数:

echo number_format($a,0,"","");
120370289

为什么会这样??

【问题讨论】:

  • $a=00713132161838; 声明整数值时的零表示该值被视为八进制值,而不是十进制值PHP Docs

标签: php integer comparison-operators


【解决方案1】:

php 中数字前导零是八进制数,它打印120370289,它是00713132161838 的十进制等价物。因此在php中有两种比较,

(`00713132161838`==713132161838) // return true
(`00713132161838`===713132161838) // return false and strict comparison
(00713132161838==713132161838) 
// this will never give you true value because 007.....8 is the octal, number first converted to decimal and comparison will be there

因此您可以使用单引号/双引号来包装数字,然后使用 intval 将它们转换为十进制整数值,您可能需要阅读 intval function in php 的更多信息

【讨论】:

  • 如果你得到你的答案,你可以接受作为答案......?
【解决方案2】:

您可以通过ltrim删除前导零

例子-

$str = ltrim($str, '0');

【讨论】:

    猜你喜欢
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 2012-04-04
    • 1970-01-01
    • 2019-07-04
    • 2014-10-25
    • 2013-07-10
    相关资源
    最近更新 更多