Codemonkey
Codemonkey

Reputation: 4807

What's the difference between $bar = boolval($foo) and $bar = (bool) $foo in php?

Same for intval / (int), floatval / (float), etc.

As far as I can make out, neither changes the original variable, and they both return the casted version. They appear to be functionally identical.

Are there edge cases where there's a difference?

Any reason to ever use one over the other?

Best practice?

I'm assuming that (bool) is "better", as I figure it's probably quicker than a function call that internally probably just does the same thing. If that's the case though, what's the point of these boolval/intval/floatval functions?

Upvotes: 16

Views: 4107

Answers (2)

Tomanhez
Tomanhez

Reputation: 89

Using boolval vs (bool) have diference in cases: If you needs to return bool and has two ints:

  • return 1 & 1 - return int
  • return (bool) 1 & 1 - throw error(using strict_types)
  • return (bool) (1 & 1) - return bool
  • return boolval(1 & 1) - return bool

Upvotes: 2

deceze
deceze

Reputation: 522175

For the most part they are identical, however there are subtle differences:

  • some functions like intval accept a second parameter ($base), which the cast syntax does not
  • a function call has a little more overhead
  • functions can be used as callbacks (e.g. array_map('intval', ..)), which is not possible with the cast syntax

Upvotes: 26

Related Questions