Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecasting vs function to convert variable type in PHP

Tags:

php

casting

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?

like image 540
Matías Cánepa Avatar asked Jun 19 '15 14:06

Matías Cánepa


People also ask

How do you convert one variable type to another in PHP?

PHP settype() Function The settype() function converts a variable to a specific type.

Which function can be used for type casting?

Explicit Type Casting Mainly in type casting can be done with these data type function: Int() : Int() function take float or string as an argument and return int type object. float() : float() function take int or string as an argument and return float type object.

How would you use typecasting in PHP to convert a string to an integer?

To convert string to integer using PHP built-in function, intval(), provide the string as argument to the function. The function will return the integer value corresponding to the string content. $int_value = intval( $string );


1 Answers

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.

like image 68
deceze Avatar answered Oct 05 '22 09:10

deceze