This article mainly shares the knowledge of PHP data type conversion.
PHP data type conversion is a forced conversion. The PHP data types that are allowed to be converted are:
(int), (integer): Convert to integer
(float), (double), (real): Convert to floating point type
(string): Convert to string
(bool), (boolean): Convert to Boolean type
(array): Convert to array
(object): Convert to object
PHP data types have three conversion methods:
(1) Add the target type enclosed in parentheses before the variable to be converted, for example:
(int) (bool) (float) (string) (array) (object) The following is an example:
<?php $num1=3.14; $num2=(int)$num1; //强制转换为int类型 var_dump($num1); //输出float(3.14) var_dump($num2); //输出int(3)
(2) Use three specific types of conversion functions, intval(), floatval(), strval(). Examples are as follows:
<?php $str="123.9abc"; $int=intval($str); //转换后数值:123 $float=floatval($str); //转换后数值:123.9 $str=strval($float); //转换后字符串:"123.9"
(3) Use the general type conversion function settype(mixed var, string type). The specific examples are as follows:
<?php $num4=12.8; $flg=settype($num4,"int"); var_dump($flg); //输出bool(true) var_dump($num4); //输出int(12)