Typecasting vs function to convert variable type in PHP

PhpCasting

Php Problem Overview


Is there any difference between typecasting and using a function to convert a variable to some type?

(float)$var VS. floatval($var)

If there are, when one of those should be used instead of the other?

Php Solutions


Solution 1 - Php

There's no difference in the resulting value, just:

  • (float) is a language feature and very quick
  • floatval() incurs the overhead of a function call (minimal, but nonetheless...)
  • floatval() as a function can be used in ways that (float) cannot, e.g. array_map('floatval', $foo)

The last point is, I believe, the main reason for floatval's existence: so each casting operation has a function equivalent, which can be useful in some circumstances.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatías CánepaView Question on Stackoverflow
Solution 1 - PhpdecezeView Answer on Stackoverflow