s.webbandit
s.webbandit

Reputation: 17000

PHP typecasting

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.

Upvotes: 33

Views: 38806

Answers (4)

Michael Fenwick
Michael Fenwick

Reputation: 2494

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.

Upvotes: 7

Deji
Deji

Reputation: 777

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.

Upvotes: 2

Igor Evstratov
Igor Evstratov

Reputation: 719

(int)$value is much faster then other ways

Upvotes: 6

xdazz
xdazz

Reputation: 160833

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

Upvotes: 34

Related Questions