Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using long int in PHP

I am trying this out, but am unable to store large value

$var = rand(100000000000000,999999999999999);
echo $var; // prints a 9 digit value(largest possible)

How to get a desired value ?

like image 391
Prashant Singh Avatar asked Dec 27 '11 16:12

Prashant Singh


People also ask

Can PHP hold the value of a long number?

An "integer" can hold the value of a "long", since they're not really the same as in Java. PHP stores numbers as integers or floats, where the size of the integer is platform dependent (but usally 32 bit, signed). If you need to represent a larger number you should use the BC Math functions.

How to cast an integer to a long in PHP?

2 Answers. To elaborate on what AgentConundrum said, there isn't a need to cast an integer to a long in PHP. PHP is a dynamic language which means that generally, for operations on fundamental types, there is no need for casting (unless it is for some explicit purpose - i.e. a float to an integer), as PHP handles it for you.

What is the size of an integer in PHP?

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit. PHP does not support unsigned integer s.

How to convert an integer to a string in PHP?

It looks easy at first because PHP provides automatic type conversion. For example, you can assign an integer value to a variable, and the type of that variable will be an integer. On the next line, you can assign a string to the same variable, and the type will change to a string.


2 Answers

From the manual:

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). 64-bit platforms usually have a maximum value of about 9E18. PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

...

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

BC Math and GMP are the (only?) way to manipulate this limitation.

like image 97
DaveRandom Avatar answered Oct 17 '22 16:10

DaveRandom


PHP ints are typically 32 bits. Other packages provide higher-precision ints: http://php.net/manual/en/language.types.integer.php

like image 5
Ned Batchelder Avatar answered Oct 17 '22 16:10

Ned Batchelder