Is there any particular difference between intval and casting to int - `(int) X`?

Viewed 86049

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 Answers

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

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

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

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.

Related