The data type conversion of PHP is a mandatory conversion. The PHP data types that are allowed to be converted are:
- (int), (integer): Convert to integer
- (float), (double), (real): Convert to float
- (string): convert to string
- (bool), (boolean): Convert to boolean type
- (array): Convert to an array
- (object): Convert to object
There are three conversion methods for PHP data types:
- Prefix the variable to be converted with the target type enclosed in parentheses
- Use 3 specific types of conversion functions, intval(), floatval(), strval() [Memory: the type of destination you want to convert + val()]
- Use the generic type conversion function settype(mixed var,string type)
The first conversion method: (int) (bool) (float) (string) (array) (object)
- <?php
- $num1=3.14;
- $num2=(int)$num1;
- var_dump( $num1); //output float(3.14)
- var_dump( $num2); //output int(3)
- ?>
The second conversion method: intval() floatval() strval()
- <?php
- $str="123.9abc";
- $int=intval($str); //The converted value: 123
- $float=floatval($str); //The converted value: 123.9
- $str=strval($float); // converted string: "123.9"
- ?>
The third conversion method: settype();
- <?php
- $num4=12.8;
- $flg=settype($num4,"int");
- var_dump( $flg); //output bool(true)
- var_dump( $num4); //output int(12)
- ?>
Reprinted from: http://www.tianzhigang.com/article.asp?id=280