views:

458

answers:

4

Hello,

Is there any particular difference between intval and (int)?

Example:

$product_id = intval($_GET['pid']);
$product_id = (int) $_GET['pid'];

Is there any particular difference between above two lines of code?

+7  A: 

intval() can be passed a base from which to convert. (int) cannot.

int intval( mixed $var  [, int $base = 10  ] )
Amber
+2  A: 

The thing that intval does that a simple cast doesn't is base conversion:

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

If the base is 10 though, intval should be the same as a cast (unless you're going to be nitpicky and mention that one makes a function call while the other doesn't). As noted on the man page:

The common rules of integer casting apply.

deceze
+1  A: 

Just minimal function call overhead i think... im not sure as i always use ($type) to cast.

prodigitalson
+3  A: 

I think there is at least one difference : with intval, you can specify which base should be used as a second parameter (base 10 by default) :

var_dump((int)"0123", intval("0123"), intval("0123", 8));

will get you :

int 123
int 123
int 83
Pascal MARTIN