Home > Article > Backend Development > How to convert variables into strings in php
php method to convert variables into strings: You can use forced type conversion, that is, add the target type enclosed in parentheses before the variable to be converted, such as [$num1=3.14;$num2 =(int)$num1].
There are three ways to convert data types in PHP:
1. Add parentheses before the variable to be converted. Target type (forced type conversion)
2. Use intval(), floatval(), strval() functions for conversion
3. Use the general type conversion function settype(mixed var, string type ) to convert
(Related learning video recommendations: java video tutorial)
Example:
The first conversion method:
<?php $num1=3.14; //字符串 $num2=(int)$num1; 转成 int 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) ?>
Related recommendations: php training
The above is the detailed content of How to convert variables into strings in php. For more information, please follow other related articles on the PHP Chinese website!