PHP is a weakly typed language, because when we declare a variable, we do not need to specify the data type it stores. However, although PHP is a weakly typed language, type conversion is still needed sometimes.
PHP allows conversion types as follows:
Conversion operator | Conversion type | Example |
boolean, bool | Convert to Boolean type | (boolean)$num,(boolean)$str |
string | Convert to string | (string)$boo,(string)$flo |
Convert to integer | (integer)$boo,(integer)$str | |
convert to floating point type | (float)$str | |
Convert to array | (array)$str | |
Convert to object | (object)$str |
The first one:
Just need to add the type name enclosed in parentheses before the variable to be converted, like the following:
<?php $num1=3.14; $num2=(int)$num1; var_dump($num1); echo "<br/>"; var_dump($num2); ?>
Code running results:
##Second type:
Use three specific types of conversion functions, intval(), floatval(), strval()<?php $a="123.9abc"; $int=intval($a); //转换后数值:123 var_dump($int); echo "<br/>"; $float=floatval($a); //转换后数值:123.9 var_dump($float); echo "<br/>"; $str=strval($float); //转换后字符串:"123.9" var_dump($str); ?>
Third type:
Use the settype() function, which can specify The variable is converted into the specified data type. The syntax is as follows:settype(mixed var,string type)
<?php $num=12.8; $flg=settype($num,"int"); var_dump($flg); //输出bool(true) echo "<br/>"; var_dump($num); //输出int(12) ?>
#When the string is converted to an integer or floating point type, if the string starts with a number , the number part will be converted to an integer first, and then the following string will be discarded; if the number contains a decimal point, the first decimal place will be taken.
PHP data type conversion example
This example will use the first and third methods to convert the specified string type and compare the two methods. The difference between them, the code is as follows:
<?php header("content-type:text/html;charset=utf-8"); //设置编码 $num='3.1415926r*r'; echo '使用(integer)操作符转换变量$num类型:'; //使用integer转换类型 echo (integer)$num .'<br/>'; echo '输出变量$num的值:'.$num.'<br/>'; //输出原始变量$num echo '使用settype函数转换变量$num类型:'; echo settype($num,'integer').'<br/>'; //使用settype函数转换类型 echo '输出变量$num的值:'.$num; //输出原始变量$num ?>
As you can see from the above example, using the integer operator can directly output The converted variable type, and the original variable does not change in any way. Instead, the settype() function returns 1, which is true, and the original variable is changed. In actual applications, you can choose the conversion method according to your own needs.
In the next section, we will explain "How to detect data type
".The above is the detailed content of Detailed explanation of php data type conversion examples. For more information, please follow other related articles on the PHP Chinese website!