33

I was wondering what is the best way to typecast a value from one type to another.

Which variant should we use:

  1. intval($value);
  2. settype($value, 'int')
  3. (int)$value

All of them produce same result.

0

4 Answers 4

34
(int)$value

saves one function call compares to intval($value) and settype($value, 'int').

And (int)$value is clean enough, so I prefer this way.

When you need to use intval($value) is that when you need to use the specified base for the conversion (the default is base 10). intval accepts a second parameter for the base for the conversion.

0
7

The answer here is to use whatever reads "cleaner" to you. Any difference in speed is going to be so minor, that worrying about it is almost certain to cost you more time than you are liable to save. What will save time, however, is having code that you can read and understand in the future.

There's an excellent article explain this very thing at Coding Horror.

0
6

(int)$value is much faster then other ways

4
  • 15
    "much faster" - please don't. Just because of such answers a lot of people think it is true
    – zerkms
    Aug 8, 2012 at 3:18
  • 4
    It's true. I've tested all ways 10 millions times and get the following results: int()$value - 2.7695989608765 s; intval($value) - 5.8383219242096 s; settype($value, 'int') - 8.035208940506 s. The calling functions in PHP is expensive Aug 22, 2012 at 4:53
  • 6
    I agree it is faster, but when you'll have 10 millions casts in your code - you'll be in worse trouble than just deciding what to use - function or type hint. So for real life the difference doesn't matter at all (for hundreds of thousands it is negligible)
    – zerkms
    Aug 22, 2012 at 9:02
  • 1
    @IgorEvstratov editing your benchmark comparisons into your answer seems a sensible action. Mar 30, 2022 at 3:49
2

It can depend on what types you're converting. PHP is already designed to convert types on-the-fly. It can convert the string '5' into the integer value 5 or float 5.0 if necessary. That's just PHP's natural type converting, but there are ways to force similar behaviours.

In many cases intval() can actually be faster than (int) typecasting, especially in string-to-integer converting. But personally, as I also write C++, I use typecasting as it is more natural and neat to me. The results, however, vary slightly in different situations. I never thought of settype() to be promising, though.

1
  • If the type is dynamic, the only way to go is settype.
    – meze
    Aug 8, 2012 at 4:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.