在PHP中处理大量数字


Handling large numbers in PHP

几分钟后,我意识到我所拥有的错误:神奇的2147483647数字,即PHP/32上integer类型的上限。我需要在我的函数中管理更大的数字:

public function albumExists($name) // e.g. 104112826372452
{
   $albums = $this->getAlbums();
   // If $name is int, search the key in $albums
   if(is_int($name) && ($found = array_key_exists($id = intval($name), $albums)))
      return ($found ? $id : false);
   // Start looking for $name as string
   foreach($album as $id => $a) if ($a->name == $name) return intval($id);
   return false; // Found nothing
}

,以便能够同时搜索idname。但是intval()总是返回上限。如何处理像104112826372452这样的大数字?想法吗?

EDIT:使用示例:

$album = $fb->createAlbum('Test Album'); // Will return album id
// The use albumExists to check if id exists
$photo1 = $fb->uploadPhoto('mypic1.png', null, $album); 
$photo2 = $fb->uploadPhoto('mypic2.png', null, 'Test Album'); // find or create

如果您将转换为整型(看起来是这样),也许您可以对其进行调整,使其纯粹基于数字而不是整型数据类型进行计算:

if(ctype_digit($name) && ($found = array_key_exists($id = $name, $albums)))
      return ($found ? $id : false);
//etc

实际上,这也应该起作用吗?

if(ctype_digit($name) && ($found = array_key_exists($name, $albums)))
      return ($found ? $name: false);
//etc

作为解决方法,您可以使用gmpbcmath函数。

不太清楚为什么要强制转换为PHP整数。当不需要使用它们进行计算时,请将数据库编号保留为字符串。并不是所有看起来像数字的东西都需要用数字来表示。

我想你真正的问题是与is_int()的差异。只需使用is_numeric()来代替它,它可以处理任意长度的数字字符串,并且不依赖于整型转换值。

int有上限,较大的数字将表示为floats,这是不精确的,因此在这种情况下使用它是一个坏主意。使用string来存储这些数字,如果需要对其进行计算,则使用BC Math扩展。

遗憾的是PHP int类型最多只能容纳2147483647,但是PHP float可以容纳10000000000000

整数

查看php.nethttp://php.net/manual/en/language.types.integer.php

PHP.net说浮点数可以精确地保存整数,最大可达10000000000000。我不确定float是否有上限。

一种选择是在64bit操作系统上运行PHP,因为大小由底层操作系统决定。这显然取决于你是否可以访问64bit硬件,有一点要注意的是,这将比使用gmp/bcmath更快,但除非你的目标是纯粹的速度,否则对你来说可能不是问题