# intval

(PHP 4, PHP 5, PHP 7)

intval변수의 정수값을 얻습니다

### 설명

int intval ( mixed `\$var` [, int `\$base` ] )

지정한 `base` 값에 따른 `var`integer값을 반환합니다. (기본 진법은 10입니다)

### 인수

`var`

정수로 변환할 스칼라 값

`base`

변환에 사용할 진법 (기본값은 10진법)

### 반환값

성공시엔 `var`의 정수 값, 실패시엔 0. 빈 배열과 객체는 0을 반환하고, 비어있지 않은 배열과 객체는 1을 반환합니다.

최대값은 시스템에 의존합니다. 32비트 시스템은 부호 있는 정수의 최대값 범위로 -2147483648에서 2147483647을 가집니다. 그러한 시스템에서 intval('1000000000000') 등은 2147483647을 반환합니다. 64비트 시스템에서 부호 있는 정수의 최대값은 9223372036854775807입니다.

문자열은 대부분 0을 반환하지만, 이는 문자열의 가장 왼쪽 문자들에 의해 결정됩니다. 정수형 변환의 기본 규칙이 적용됩니다.

### 예제

Example #1 intval() 예제

다음 예제는 32비트 시스템입니다.

``` echo intval(42);                      // 42echo intval(4.2);                     // 4echo intval('42');                    // 42echo intval('+42');                   // 42echo intval('-42');                   // -42echo intval(042);                     // 34echo intval('042');                   // 42echo intval(1e10);                    // 1410065408echo intval('1e10');                  // 1echo intval(0x1A);                    // 26echo intval(42000000);                // 42000000echo intval(420000000000000000000);   // 0echo intval('420000000000000000000'); // 2147483647echo intval(42, 8);                   // 42echo intval('42', 8);                 // 34?> ```

### 주의

Note:

`var` 인수가 문자열이 아니면 `base` 인수는 아무런 영향을 주지 않습니다.

### 참고 add a note

### User Contributed Notes 40 notes

172
Ken
7 years ago
``` Not mentioned elsewhere: intval(NULL) also returns 0. ```
27
leon at leonidasjp dot nl
2 years ago
``` 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.<?phpecho intval('1e5');?>will return 1 on PHP 5.6 and PHP 7.0,but it will return 100000 on PHP 7.1. ```
75
winbill at hotmail dot com
8 years ago
``` Be careful :<?php\$n="19.99";print intval(\$n*100); // prints 1998print intval(strval(\$n*100)); // prints 1999?> ```
32
zak at php dot net
19 years ago
``` 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 ```
34
spoon_reloaded at gmail dot com
10 years ago
``` 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(): <?php echo intval("0x1a", 0), "\n"; // hex; prints "26" echo intval("057", 0), "\n"; // octal; prints "47" echo intval("42", 0), "\n"; // decimal; prints "42" ?> ```
17
Ben Laurienti
13 years ago
``` 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 . "<br />\n";echo \$test2 . "<br />\n";echo \$test3 . "<br />\n";expected output:199919991999actual output199919981999Appears 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. ```
11
espertalhao04 at hotmail dot com
6 years ago
``` if you want to take a number from a string, no matter what it may contain, here is a good solution:<?phpfunction int(\$s){return(int)preg_replace('/[^\-\d]*(\-?\d*).*/','\$1',\$s);}echo int('j18ugj9hu0gj5hg');//output: 18?>this example returns an int, so it will follow the int rules, and has support for negative values.<?phpfunction int(\$s){return(\$a=preg_replace('/[^\-\d]*(\-?\d*).*/','\$1',\$s))?\$a:'0';}echo int('j-1809809808908099878758765ugj9hu0gj5hg');//output: -1809809808908099878758765?>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. ```
tuxedobob at mac dot com
15 years ago
``` 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. :) ```
mkamerma at science dot uva dot nl
13 years ago
``` 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). ```
taylorsarrafian at gmail dot com
4 years ago
``` beware:<?php   // observe the following   echo intval( strval( -0.0001 ) ); // 0   echo intval( strval( -0.00001 ) ); // -1   // this is because   echo strval( -0.0001 ); // -.0001   echo strval( -0.00001 ); // -1.0E-5   // thus beware when using   function trunc2_bad( \$n ) {      return intval( strval( \$n * 100 ) / 100 );   }   // use this instead   function trunc2_good( \$n ) {      return intval( floatval( strval( \$n * 100 )  ) / 100 );   }?> ```
yves
8 years ago
``` 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  intval('42', 8); // => 34  intval(42, 8);   // => 42 !?>PHP considers the 42 as being already an integer, and doesn't apply any conversion. And supplying<?php  intval(49, 8);  // => 49 !?>produces no error and no warning. ```
simon at npkk dot cz
13 years ago
``` 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). ```
chinmay235 at gmail dot com
1 year ago
``` <?phpecho intval("10 days");          //10echo intval("days 10");          //0?> ```
Anthony
1 year ago
``` The binary notation is NOT supported until php7.2<?php                         // PHP <7.2 | PHP >=7.2echo intval(0b11);       //    3     |     3echo intval(-0b11);      //   -3     |    -3echo intval('0b11');     //    0     |     0echo intval('-0b11');    //    0     |     0echo intval('0b11', 0);  //    0     |     3echo intval('-0b11', 0); //    0     |    -3?> ```
-1
Nibs Niven
1 year ago
``` The example is wrong for PHP 7.1intval('1e10') does not return 1 as the example states, it returns 10000000000. This has broken at least one library I know of (BEncodeLib). ```
pfreet at gmail dot com
6 years ago
``` Do not use intval() when you really want round(). This is due to how PHP handles precision. echo number_format(8.20*100, 20), "<br />";echo intval(8.20*100), "<br />";echo floor(8.20*100), "<br />";echo round(8.20*100), "<br />";819.99999999999988631316819 819820 ```
Robin Y. Millette http://rym.waglo.com
16 years ago
``` 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 ===. ```
-2
anonymous at place dot com
13 years ago
``` 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 . "<br />\n";echo \$test3 . "<br />\n"; ```
-2
gregrobson at gmail dot com
7 years ago
``` I just wanted to be sure that a string was going to be valid if I intval'ed it. This regular expression matches:0Any 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 ;)<?php/** * Loops through each non-array element and actions a function. * * @return boolean|integer TRUE if the value matches as an integer, FALSE if * an error occured or 0 if not match was found. */public function validate(\$value){    \$value = preg_match('/^(0|(-{0,1}[1-9]\d*))\$/', trim(\$value));    if (\$value == 1)        return true;    else        return \$value;}?>If you use intval() now, you are merely changing the data type. ```
-2
Seally
11 years ago
``` Re: nobodyisperfect88 at hotmail dot dejay 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) ```
-2
bert at nospam dot thinc dot nl
10 years ago
``` If you need the reverse function of intval(), the code hereunder might be helpfull.<?phpfunction itoa( \$ii, \$radix=10, \$stritoa="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabc" ) {    if ( \$radix > strlen( \$stritoa ) )    //    does request makes sense?        return "";    //    think of your own way to handle this case    \$sign = \$ii<0 ? "-": "";    \$ii = abs( \$ii );    \$rc = "";    do {        \$rc .= \$stritoa[ \$ii % \$radix ];        \$ii = floor( \$ii / \$radix );        } while ( \$ii >0 );    return \$sign . strrev( \$rc );    }?> ```
-3
aryel at redtwilightNO dot comSPAM dot brNOT
12 years ago
``` 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 ```
-2
Anonymous
15 years ago
``` When trying to read 32bit values (32 bit limitation depends on the word size of your machine)  from a string that is represented in hex with the high bit set, eg. F9833234 intval returns -1. The reason is the sign bit being set. This number is larger than can be saved in a signed int.The way around this is to read the value in using two calls to intval.eg. \$val = intval(substr(\$str,0,4), 16); // read high 16 bit word\$val <<= 16; // shift hi word correct position\$val |= intval(substr(\$str, 4, 4), 16); //  read low 16 bit word ```
-2
jplevene at netscape dot net
5 years ago
``` I have found intval very useful for database security.If you are passing a value via- Data from user input- Data that you have stored RAW on DB (witch is the best way) and you are using on a new sql statment- Data from unknown/other originand the data is supposed to be an integer, I always run it through intval before I put it into the query (or you could use real_escape_string)This prevents hackers from passing the variable as an SQL statement instead of a number in order to attack your database. ```
-3
mkamerma at science dot uva dot nl
13 years ago
``` 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.<?php/* encode integer as 7bit with has-more bit numeral,    ordered lowest byte first. */function encode_7bhm(\$int) {  if (\$int==0) return chr(0); // shortcut  \$ret = "";  while(\$int != 0) {    \$high = floor(\$int / 128);     // overflow for this round    \$low = \$int - (\$high * 128); // 7 bit numeral    if (\$int > 0) {      if (\$high > 0) { \$low = \$low + 128; } // has-more flag      \$ret .= chr(\$low); } //encode    \$int = \$high;  // set overflow as next round's number  }  return \$ret;}/* decode a 7bit with has-more bit numeral,    ordered lowest byte first. */function decode_7bhm(\$hmb) {  \$ret = 0;  \$pos = 0;  \$high = 1;  while(\$high == 1) {    \$byte = ord(substr(\$hmb, \$pos, 1));    \$high = floor(\$byte/128); // gets has-more flag    \$low = \$byte - (\$high*128);    \$ret += \$low * pow(128, \$pos++); // decode  }  return \$ret;}?>This codec pair is also quite useful when needing to write ints to files, as this is a low-numeral biased encoding: most of the time this will only require 8 or 16 bit rather than the 32 bits an int will use in fixed-length encoding.The encoding range:  1 byte  - 0 through 128 (2^7)  2 bytes - 129 through 16,384 (2^14)  3 bytes - 16,385 through 2,097,152 (2^21)  4 bytes - 2,097,153 through 268,435,456 (2^28)while indeed a 32 bit encoded variable length integer will be lower than maxint, rather than needing a new 32 bit block to represent higher range only 8 more bits are required to represent this higher number (for completeness the range of representation by bytes 5-8 are listed):  5 bytes - 268,435,457 through 34,359,738,368 (2^35)  6 bytes - 343,59,738,369 through 4,398,046,511,104 (2^42)  7 bytes - 4,398,046,511,105 through 562,949,953,421,312 (2^49)  8 bytes - 562,949,953,421,313 through 720,57,594,037,927,936 (2^56)Also for completeness, the function to read a 7 bit with has-more bit from a filepointer:<?php// read a 7bhm numeral from filefunction read_7bhm(\$fp) {  \$bytestring = "";  \$high = 1;  while(\$high==1) {    \$byte = fread(\$fp, 1);    \$high = floor(ord(\$byte)/128); // check for has-more bit    \$bytestring .= \$byte;  }  return decode_7bhm(\$bytestring); }?> ```
-5
yhoko at yhoko dot com
11 years ago
``` Note that this function behaves different in PHP4/5 when parsing NAN-values. Try the following example:<?php die( "Result = " . intval( NAN ) ); ?>- In PHP 4 the result is 0- In PHP 5 the result is 2^31 (running on 32bit)Yhoko ```
-6
michiel ed thalent nl
11 years ago
``` A function to get an integer from everywhere in a string (concatenated or not).<?phpfunction str2int(\$string, \$concat = true) {    \$length = strlen(\$string);        for (\$i = 0, \$int = '', \$concat_flag = true; \$i < \$length; \$i++) {        if (is_numeric(\$string[\$i]) && \$concat_flag) {            \$int .= \$string[\$i];        } elseif(!\$concat && \$concat_flag && strlen(\$int) > 0) {            \$concat_flag = false;        }            }        return (int) \$int;}echo var_dump(str2int('sh12apen11')); // int(12)echo var_dump(str2int('sh12apen11', false)); // int(1211)echo var_dump(str2int('shap99en')); // int(99)echo var_dump(intval('shap99en')); // int(0)?> ```
-5
lrdsatyr8 at hotmail dot com
11 years ago
``` If you just want to get the integer value of a number without all the hassle, just use intval()... like so:\$a1 = 10.4;\$a2 = -12.5;\$a3 = 44.1238503;print intval(\$a1);   // returns 10print intval(\$a2);   // returns -12print intval(\$a3);   // returns 44it's that easy! ```
-6
jay at w3prodigy dot com
11 years ago
``` Note:\$int = 0.99999999999999999;echo intval(\$int); // returns 1and\$int = 0.9999999999999999;echo intval(\$int); // returns 0 ```
-3
phpben hood id au
11 years ago
``` 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:<?php\$tmp_array = "123,232,141";if (intval(\$tmp_array) === \$tmp_array){    echo "'".intval(\$tmp_array)."' equals '\$tmp_array'\n";}else{    echo "'".intval(\$tmp_array)."' does not equal '\$tmp_array'\n";}?> ```
-4
simon at npkk dot cz
13 years ago
``` intval() returns maxint on number_in_string, if the result would be bigger than it. But for float returns the signed 32 bit integer with the "same" value: <?php \$num=-1000; print(\$num."\n"); \$i_str=sprintf("%u",\$num); print(\$i_str."\n"); \$i1=intval(\$i_str); print(\$i1."\n"); \$i2=intval(floatval(\$i_str)); print(\$i2."\n"); ?> prints: -1000 4294966296 2147483647 -1000 ```
-5
maciek dot iwanowskis at glasspartnership dot co dot uk
12 years ago
``` It seems that if you're trying to cast to integer (or use intval()) on integer of value bigger then 2147483646 it's hard to predict returned value. ```
-8
vizigr0u at gmail dot com
12 years ago
``` intval used on bools returns either 1 or 0I usually use this to properly set bools in my tables (assuming you use some kind of int like tinyints as booleans) : <?php \$myvar = 'right value';mysql_query('INSERT INTO mytable (activated) VALUES(' . intval(\$myvar === 'right value') . ')');?> ```
-4
ittasks at gmail dot com
10 years ago
``` when converting some optional form values to positive integers and to be on the safe side, you can use this: <?php \$q=intval("0".\$_REQUEST['q']); ?> ```
-5
jazeik at gmail dot com
12 years ago
``` @kris:If you had followed the following links:"The common rules of integer casting apply." => http://us.php.net/manual/en/language.types.integer.php"See String conversion to numbers" => http://us.php.net/manual/en/language.types.integer.phpThen you would have found the following: "The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used."So this behaviour is a feature not a bug. The following code will work:<?php\$tmp_array = str_replace(",", "", "123,232,141");if(intval(\$tmp_array) == \$tmp_array){    echo intval(\$tmp_array) . " equals \$tmp_array\n"; }else{    echo intval(\$tmp_array) . " does not equal \$tmp_array\n"; }?>Output:123232141 equals 123232141 ```
-9
Anonymous
13 years ago
``` Operating on integers gives puzzling results--which don't seem to have to do with the number of bits...<?phpecho intval(1e10);  // -1 on my system; 1410065408 in the exampleecho intval(1e5); // 100000 (my own example: lower number--works all right)echo intval(4e9);  // -294967296 ! (my own example: somewhere in the middle)echo intval(42000000);  // 42000000 (as in the manual; reasonable)echo intval(420000000000000000000);  // -1 on my system at least. 0 in the example// ...and yet still odder...echo intval(4200000000);  // -94967296! (my own example: somewhere in between)?> ```
-7
14 years ago
``` 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. ```
-7
jeremy at cfegames dot com
9 years ago
``` When retrieving numbers or integers from a MySQL DB, it's best to use intval(), or it will continue to be a string.<?phpwhile(\$row = mysql_fetch_array(\$check){ \$_SESSION['id'] = inval(\$row['id']); \$user_id = intval(\$_SESSION['id']); // Not sure if you need to do it again, but doesn't hurt.}is_int(\$_SESSION['id'])is_int(\$user_id)is_string(\$_SESSION['id'])is_string(\$user_id)// Outputtruetruefalsefalse?> ```
-7
nlong121 at gmail dot com
5 years ago
``` As a note using intval() as a check for string comparison will not work\$string="Pork";\$test=intval(\$string);echo \$test.'=='.\$string;if(\$string==\$test)    {    echo '::Test PASS';        }else{    echo '::Test FAIL';        }if(is_numeric(\$string))    {    echo '::Test PASS';        }else{    echo '::Test FAIL';        }/*Produces 0==Pork :: Test PASSis_numeric(Pork) :: Test FAIL ```
-8
Er.ellison
3 years ago
``` i guess one of the important usage of intval is in links , because : imagine that u have a function that uses get method (for example an integer id ) to retrieve the data from DB , so for example if you get "  id=58  " in your link and put that in u'r function that retrieves data from DB , that's fine , it works wellbut what if some body put the  "  id=58djkdjsbvjkdsbvjkdbs " in the link ON PURPOSE !in such situation and condition he will get an Database error because u'r function retrieves Data from DB so it good to be use intval in such situationsbecause if u use that u gonna be sure that what ever that passes from u'r DB related function is just a integer , No text and any strange character !let me show u by example\$id = 12dfjgdfjgnd; echo \$id  // output will be : 12dfjgdfjgndecho intval(\$id) // output will be  : 12 ``` 