百科狗-知识改变命运!
--

intval() - php 变量处理函数

梵高1年前 (2023-11-21)阅读数 24#技术干货
文章标签变量

intval()

(PHP 4, PHP 5, PHP 7)

intval() - php 变量处理函数

获取变量的整数值

说明

intval(mixed $var[,int $base= 10]): int

通过使用指定的进制$base转换(默认是十进制),返回变量$var的integer数值。intval()不能用于 object,否则会产生E_NOTICE错误并返回 1。

参数

$var

要转换成 integer 的数量值

$base

转化所使用的进制

Note:

如果$base是 0,通过检测$var的格式来决定使用的进制:

  • 如果字符串包括了"0x"(或"0X")的前缀,使用 16 进制(hex);否则,
  • 如果字符串以"0"开始,使用 8 进制(octal);否则,
  • 将使用 10 进制(decimal)。

返回值

成功时返回$var的 integer 值,失败时返回 0。空的 array 返回 0,非空的 array 返回 1。

最大的值取决于操作系统。 32 位系统最大带符号的 integer 范围是-2147483648 到 2147483647。举例,在这样的系统上,intval('1000000000000')会返回 2147483647。64 位系统上,最大带符号的 integer 值是 9223372036854775807。

字符串有可能返回 0,虽然取决于字符串最左侧的字符。使用整型转换的共同规则。

范例

Example #1intval()例子

下面的例子运行于 32 位系统上。

注释

Note:

除非$var是一个字符串,否则$base不会起作用。

更新日志

版本说明
5.1.0当传入的$var是 object,将会抛出E_NOTICE并返回 1。

参见

  • boolval() 获取变量的布尔值
  • floatval() 获取变量的浮点值
  • strval() 获取变量的字符串值
  • settype() 设置变量的类型
  • is_numeric() 检测变量是否为数字或数字字符串
  • 类型转换的判别
  • BCMath 任意精度数学函数
Not mentioned elsewhere: intval(NULL) also returns 0.
It seems intval is interpreting valid numeric strings differently between PHP 5.6 and 7.0 on one hand, and PHP 7.1 on the other hand.

will return 1 on PHP 5.6 and PHP 7.0,
but it will return 100000 on PHP 7.1.
Be careful : 
intval converts doubles to integers by truncating the fractional component of the number.
When dealing with some values, this can give odd results. Consider the following:
print intval ((0.1 + 0.7) * 10);
This will most likely print out 7, instead of the expected value of 8.
For more information, see the section on floating point numbers in the PHP manual (http://www.php.net/manual/language.types.double.php)
Also note that if you try to convert a string to an integer, the result is often 0.
However, if the leftmost character of a string looks like a valid numeric value, then PHP will keep reading the string until a character that is not valid in a number is encountered.
For example:
"101 Dalmations" will convert to 101
"$1,000,000" will convert to 0 (the 1st character is not a valid start for a number
"80,000 leagues ..." will convert to 80
"1.4e98 microLenats were generated when..." will convert to 1.4e98
Also note that only decimal base numbers are recognized in strings.
"099" will convert to 99, while "0x99" will convert to 0.
One additional note on the behavior of intval. If you specify the base argument, the var argument should be a string - otherwise the base will not be applied.
For Example:
print intval (77, 8);  // Prints 77
print intval ('77', 8); // Prints 63
Here is a really useful undocumented feature:
You can have it automatically deduce the base of the number from the prefix of the string using the same syntax as integer literals in PHP ("0x" for hexadecimal, "0" for octal, non-"0" for decimal) by passing a base of 0 to intval(): 
You guys are going to love this. I found something that I found quite disturbing.
$test1 = intVal(1999);
$amount = 19.99 * 100;
$test2 = intVal($amount);
$test3 = intVal("$amount");
echo $test1 . "
\n"; echo $test2 . "
\n"; echo $test3 . "
\n"; expected output: 1999 1999 1999 actual output 1999 1998 1999 Appears to be a floating point issue, but the number 1999 is the only number that I was able to get to do this. 19.99 is the price of many things, and for our purpose we must pass it as 1999 instead of 19.99.
The binary notation is NOT supported until php7.2 
if you want to take a number from a string, no matter what it may contain, here is a good solution:

this example returns an int, so it will follow the int rules, and has support for negative values.

this one returns a string with just the numeric value.
it also supports negative values.
the latter is better when you have a 32 bit system and you want a huge int that is higher than PHP_MAX_INT.
Sometimes intval just won't cut it. For example if you want to use an unsigned 32-bit int and need all 32 bits. Recently, I wrote a little script that took and integer and converted it to an IP address. After realizing I couldn't just mod the whole thing, since the sign bit throws it off (and compensating for that), we ran into a problem where if it was entered into a form, the value somehow wasn't converted to an integer properly, at least not implicitly. The solution for this, and the way I recommend converting a string to an integer, is:
$num = $num + 0;
and PHP will leave your number alone; it'll just know it's a number. Such is the fun of a loosely-typed language. :)
As addendum, the "if ($int > 0)" check in the encode function is redundant. It doesn't do anything bad to keep it in since it will always be true when reaching that point, but it's a meaningless conditional this way. It's a remnant from when I tried to write the function in terms of bitshifts, which could lead to negative ints when shifting if the 32nd bit was set (instead of always padding with 0's when using >> it pads with 1's leading to negative ints).
Do not use intval() when you really want round(). This is due to how PHP handles precision. 
echo number_format(8.20*100, 20), "
"; echo intval(8.20*100), "
"; echo floor(8.20*100), "
"; echo round(8.20*100), "
"; 819.99999999999988631316 819 819 820
The behaviour of intval() is interesting when supplying a base, and you better check your intval base-based expressions, as it is counter-intuitive.
As the example shows

PHP considers the 42 as being already an integer, and doesn't apply any conversion. And supplying

produces no error and no warning.
Still have on mind, that if you convert big numbers by adding zero, PHP makes automatic "to a float" conversion, so it is same as floatVal(). So if the number is realy big (over 13 digits), you can lose preciosity. Do not use it for such long numbers, if all bits do matter (IPv6 addresses and similar).
The example is wrong for PHP 7.1
intval('1e10') does not return 1 as the example states, it returns 10000000000. This has broken at least one library I know of (BEncodeLib).
beware: 
Rob_Kohr at no_need_to_email dot me dot com
11-Nov-2002 12:24   
[snip]
$var=intval("122.5");
//$var==122
This is nice if you want to turn a double into an int automatically rounding down
Hum, I had a bug earlier today, involving ===. Coming from a c++ background, I can't help testing for types. I was using floor() to get an integer from a division by 2, and comparing that to a known integer from a for loop. Well, first I changed the === to == because the test would always be false otherwise. Next, I looked up this function, and converted most of my floor() calls to intval() calls, because I really meant to get an int, and not a float with no decimal part. So I have to disagree with the editor note here. Oh, and I'm comfortably back to using ===.
Re: nobodyisperfect88 at hotmail dot de
jay at w3prodigy dot com had it right. I believe it is an issue with the floating point registers on computers, which have a precision of about 17 digits. When you get more precise than that, it rounds.
Since the second example can fit in the register, no rounding occurs, and PHP can truncate the portion after the decimal. However, the system automatically rounds the first example to 1, which is what PHP returns.
(Tested on Windows XP 32bit)
I just wanted to be sure that a string was going to be valid if I intval'ed it. This regular expression matches:
0
Any positive integer (no + sign)
Any negative integer (with a - sign)
It does not match a leading 0 or any other character. You are advised to strip out commas, trim the string and check range yourself ;)

If you use intval() now, you are merely changing the data type.
re: Disturbing issue with intval()
It's probably just good practice to round decimals anyways. i.e...
$amount = round(19.99 * 100);
$test2 = intVal($amount);
$test3 = intVal("$amount");
echo $test2 . "
\n"; echo $test3 . "
\n";
If you need the reverse function of intval(), the code hereunder might be helpfull. 
Since integers are stored on multiple bytes in the memory in binary format, once an signed long integer reaches the maximum value of 2147483646 (which is the maximum value that 8 bits of memory, size of a long int, can store, binary-wise), atleast on C/C++ the number starts to roll back, going gradually to ...45, ...45 and eventually reaching a negative value. Some REALLY large values will return -1, probably because PHP simply rejects the number, though I'm not sure why.
For further info:
http://www.rwc.uc.edu/koehler/comath/13.html
When you need to work with integer values that exceed maxint, the following functions may be of use to you - they form a codec pair for integers of variable length rather than fixed length, encoded in a byte as a 7 bit numberal with a 1 bit has-more flag, indicating that the next byte encodes a higher order part of the same number still. 
Note:
$int = 0.99999999999999999;
echo intval($int); // returns 1
and
$int = 0.9999999999999999;
echo intval($int); // returns 0
intval used on bools returns either 1 or 0
I usually use this to properly set bools in my tables 
(assuming you use some kind of int like tinyints as booleans) : 
Note that this function behaves different in PHP4/5 when parsing NAN-values. Try the following example:

- In PHP 4 the result is 0
- In PHP 5 the result is 2^31 (running on 32bit)
Yhoko
Operating on integers gives puzzling results--which don't seem to have to do with the number of bits... 
Say you have a string $s="3763328634" to be used as a key into the database, intval() this string will result in a different,smaller number (depends on the machine/OS). To keep the number intact but as an int/long type, do $s +=0; instead.
when converting some optional form values to positive integers and to be on the safe side, you can use this: 
kris at mha dot ca:
Implicit typing. This is a feature, not a bug.
The == operator will convert your string to an int automatically (in this case) so that it is really comparing 123 and 123, which is of course the same.
If you use the === operator then this will not occur, as it will only match on the same value and type. This works as expected:

prints:
-1000
4294966296
2147483647
-1000
When retrieving numbers or integers from a MySQL DB, it's best to use intval(), or it will continue to be a string.

鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com

免责声明:我们致力于保护作者版权,注重分享,当前被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理!邮箱:344225443@qq.com)

图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)