Using PHP, what’s the fastest way to convert a string like this: '123' to an integer?
Why is that particular method the fastest? What happens if it gets unexpected input, such as 'hello' or an array?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’ve just set up a quick benchmarking exercise:
On average, calling intval() is two and a half times slower, and the difference is the greatest if your input already is an integer.
I’d be interested to know why though.
Update: I’ve run the tests again, this time with coercion
(0 + $var)Addendum: I’ve just come across a slightly unexpected behaviour which you should be aware of when choosing one of these methods:
Tested using PHP 5.3.1