Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Variable Handling Functions : intval

intval

Get the integer value of a variable (PHP 4, PHP 5)
int intval ( mixed var [, int base] )

Example 2587. intval() examples

The following examples are based on a 32 bit system.

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

Related Examples ( Source code ) » intval







Code Examples / Notes » intval

ben laurienti

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:
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.


mkamerma

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 file
function 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); }
?>


24-may-2004 04:38

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


simon

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).

tuxedobob

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. :)


adspeed.com

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.

robin y. millette http://rym.waglo.com

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 ===.


anonymous

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";


david

Re: Ben Laurienti, Disturbing issue with intval()
This may make things a little more clear for you:
<?php
$amount = 19.99 * 100;
printf("%.13f", $amount); // Outputs : 1998.99999999999981998
?>
Remember that casting floats to ints rounds towards zero, so these are all functionally the same producing 1998:
echo (int)$amount;
echo intVal($amount);
echo (int) 1998.99999999999981998;
Computers cannot store many floating point values to exact precision. For this reason it is generally recommended to never work with currencies in floating point types, and use integers (work in cents), or use some other method. Using floats will have all kinds of rounding and comparison issues. 19.99 will not be the only number to surprise you!


27-apr-2006 06:36

Operating on integers gives puzzling results--which don't seem to have to do with the number of bits...
<?php
echo intval(1e10);  // -1 on my system; 1410065408 in the example
echo 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)
?>


kris

More intval wierdness (tested with PHP 5.2.3 and 4.3.10).  
<?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";
}
?>
Output:
'123' equals '123,232,141'
Odd.  Not what was expected.  Maybe if I put it into a temporary variable it will normalize itself.
<?php
$tmp_array = "123,232,141";
$tmp = intval($tmp_array);
if ($tmp == $tmp_array)
{
   echo "'$tmp' equals '$tmp_array'\n";
}
else
{
   echo "'$tmp' does not equal '$tmp_array'\n";
}
?>
Output:
'123' equals '123,232,141'
I don't know if this is a feature, or a bug in PHP (I would certainly classify this as a bug, but since it is in both PHP 4 and PHP 5 maybe not).  If it is a feature, could someone explain it to me?


maciek dot iwanowskis

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.

simon

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:
<?
$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


cleong

intval() handles overflow differently depending on the type of the argument.
intval('10000000000') = 2147483647
intval(1e10) = 1410065408
intval(float) yields essentially non-defined result when the argument is beyond the range of int.


vizigr0u

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) :
<?php
$myvar = 'right value';
mysql_query('INSERT INTO mytable (activated)
VALUES(' . intval($myvar === 'right value') . ')');
?>


zak

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


aryel

Indeed, as stated by David, 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


lrdsatyr8

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 10
print intval($a2);   // returns -12
print intval($a3);   // returns 44
it's that easy!


spectator

For hexadecimal value...
(Ex, RGB color value => each R,G,B integer value)
---------------------------------------
<?
$rgb = '#E7A3EF';
$r = intval(substr($rgb,1,2),16);
$g = intval(substr($rgb,3,2),16);
$b = intval(substr($rgb,5,2),16);
?>
RGB : <?= $rgb ?>
R : <?= $r ?>
G : <?= $g ?>
B : <?= $b ?>
---------------------------------------
=> RGB : #E7A3EF
R : 231
G : 163
B : 239


mkamerma

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).

jazeik

@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.php
Then 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


shermy

<?php
$tmp_array = "123,232,141";
if (strval(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:
'123' does not equal '123,232,141'


Change Language


Follow Navioo On Twitter
debug_zval_dump
doubleval
empty
floatval
get_defined_vars
get_resource_type
gettype
import_request_variables
intval
is_array
is_binary
is_bool
is_buffer
is_callable
is_double
is_float
is_int
is_integer
is_long
is_null
is_numeric
is_object
is_real
is_resource
is_scalar
is_string
is_unicode
isset
print_r
serialize
settype
strval
unserialize
unset
var_dump
var_export
eXTReMe Tracker