php method to change type: 1. Convert to integer through (int) or (integer); 2. Convert to floating point type through (float), (double) or (real); 3. Convert to floating point type through ( string) into a string; 4. Convert into a Boolean type through (bool) or (boolean); 5. Convert into an array through (array); 6. Convert into an object through (object).
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, Dell G3 computer.
php How to change the type?
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):转换成整形 (float)、(double)、(real):转换成浮点型 (string):转换成字符串 (bool)、(boolean):转换成布尔类型 (array):转换成数组 (object):转换成对象
There are three conversion methods for PHP data types:
Add the target type enclosed in parentheses before the variable to be converted
Use 3 specific Type conversion functions, intval(), floatval(), strval()
Use the general 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); //输出float(3.14) var_dump($num2); //输出int(3) ?>
The second conversion Method:
intval() floatval() strval()
<?php $str="123.9abc"; $int=intval($str); //转换后数值:123 $float=floatval($str); //转换后数值:123.9 $str=strval($float); //转换后字符串:"123.9" ?>
The third conversion method:
settype();
<?php $num4=12.8; $flg=settype($num4,"int"); var_dump($flg); //输出bool(true) var_dump($num4); //输出int(12) ?>
Supplement:
Judge string All composed of numbers
<?php $str = "123" if(ereg('^[0-9]+$', $str)) { // true } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to change the type in php. For more information, please follow other related articles on the PHP Chinese website!