Throughout much of the code I review, I often see things such as:
// $myvar could be anything
if (intval($myvar) > 0) {
// do stuff
}
Or similarly:
if ($myvar != null && intval($myvar) > 0) {
// do stuff
}
In an ongoing quest to produce more elegant and less-wasteful code, I am wondering if it is necessary to call intval(), for example, when performing a numeric comparison. My understanding from reading the documentation and from various responses here is that when a numeric comparison is asked for, it checks the type of the var and then performs either an integer cast or a string conversion depending on what it finds — or are these the same as far as PHP is concerned, operations-wise?
Based on that, it seems the least expensive way is to tell PHP to cast it directly as an integer, as such:
if ((int)$myvar > 0) {
// do stuff
}
However, I almost never see it written that way. Am I missing anything? Does PHP automatically do this any time it seems a comparison operator?
I realize in 99.9% of situations it is sufficient to just perform the comparison and let PHP type juggle on its own, but I see this so often that either I am missing something or many others are!
You haven’t given a reason to cast at all:
will have the same effect. Either way, non-numeric strings can be coerced to 0 (this is one of PHP’s many strange design choices), and numeric strings are coerced to the number they represent. Thus after:
the following are identical (and false):
Of course, casting to
intmay be useful in other situations. Another useful function isis_numeric, which checks for a number or numeric string.