I need to simulate a ∞ in PHP.
So that min(∞,$number)
is always $number
开发者_开发问答.
I suppose that, for integers, you could use PHP_INT_MAX
, the following code :
var_dump(PHP_INT_MAX);
Gives this output, on my machine :
int 2147483647
But you have to be careful ; see Integer overflow (quoting) :
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.
And, from the Floating point numbers documentation page :
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).
Considering the integer overflow, and depending on your case, using this kind of value might be a better (?) solution...
Use the constant PHP_INT_MAX
.
http://php.net/manual/en/language.types.integer.php
You could potentially use the PHP_INT_MAX
constant (click for PHP manual docs).
However, you may want to think about whether you really need to use it - it seems like a bit of an odd request.
PHP actually has a predefined constant for "infinity": INF
. This isn't true infinity, but is essentially the largest float value possible. On 64-bit systems, the largest float is roughly equal to 1.8e308
, so this is considered to be equal to infinity.
$inf = INF;
var_dump(min($inf,PHP_INT_MAX)); // outputs int(9223372036854775807)
var_dump(min($inf,1.79e308)); // outputs float(1.79E+308)
var_dump(min($inf,1.799e308)); // outputs float(INF)
var_dump(min($inf,1.8e308)); // outputs float(INF)
var_dump($inf === 1.8e308); // outputs bool(true)
Note, any number with a value larger than the maximum float value will be cast to INF
. So therefore if we do, var_dump($inf === 1e50000);
, this will also output true
even though the maximum float is less than this.
I suppose, assuming this is an integer, you could use PHP_INT_MAX constant.
min($number, $number + 1) ??
In Perl you can use
$INF = 9**9E9;
which is larger than any value you can store in IEEE floating point numbers. And that really works as intended: any non-infinite number will be smaller than $INF
:
$N < $INF
is true for any "normal" number $N
.
Maybe you use it in PHP too?
min($number,$number)
is always $number
(also true for max()
of course).
If your only concern is comparison function then yes, you can use array(), it will be always larger then any number
like
echo min(array(), 9999999999999999);
or
if (array() > 9999999999999999) {
echo 'array won';
} else {
echo 'number won';
}
精彩评论