20

What is the better option:

// Option 1:
$intValue = (int) $numericValue;

// Option 2:
$intValue = intval($numericValue);

Is there any difference between these two lines, and which should be used in which situation?

Rene Terstegen
  • 7,911
  • 18
  • 52
  • 74

2 Answers2

22
  1. intval is slower than casting to int (it's a function)
  2. intval can accept a base if its first parameter is a string

Since the second item is really obscure, objectively we should say that intval is simply "worse".

However, personally I like reading intval($var) better than (int)$var (the latter may also require wrapping in additional parens) and since if you are converting to int inside a loop you are definitely doing something wrong, I use intval.

Jon
  • 428,835
  • 81
  • 738
  • 806
5

All behaviour explained here along with GOTCHAS...

http://php.net/manual/en/function.intval.php

http://www.php.net/manual/en/language.types.type-juggling.php

DhruvPathak
  • 42,059
  • 16
  • 116
  • 175