Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one use intval and when int [duplicate]

Tags:

php

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?

like image 910
Rene Terstegen Avatar asked Mar 17 '11 13:03

Rene Terstegen


1 Answers

  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.

like image 123
Jon Avatar answered Sep 17 '22 15:09

Jon