Conversion and formatted output of variable types in PHP
In PHP, variable types can be converted to each other, which is useful for processing data and output results very useful. At the same time, formatted output can make the data more readable and meet specific display needs.
1. Variable type conversion
Code example:
$str = "123"; $int1 = (int)$str; // 使用强制类型转换 $int2 = intval($str); // 使用intval()函数 echo $int1; // 输出 123 echo $int2; // 输出 123
Code example:
$int = 123; $str1 = (string)$int; // 使用强制类型转换 $str2 = strval($int); // 使用strval()函数 echo $str1; // 输出 "123" echo $str2; // 输出 "123"
Code example:
$str = "3.14"; $float1 = (float)$str; // 使用强制类型转换 $float2 = floatval($str); // 使用floatval()函数 echo $float1; // 输出 3.14 echo $float2; // 输出 3.14
Code example:
$float = 3.14; $str1 = (string)$float; // 使用强制类型转换 $str2 = strval($float); // 使用strval()函数 echo $str1; // 输出 "3.14" echo $str2; // 输出 "3.14"
Code example:
$arr = array('Hello', 'World'); $str = implode(' ', $arr); echo $str; // 输出 "Hello World"
2. Formatted output
Code example:
$num = 1234.56; $format_num = number_format($num); echo $format_num; // 输出 "1,234.56"
Code example:
$date = date('Y-m-d H:i:s'); echo $date; // 输出当前的日期和时间,例如 "2022-01-01 10:00:00"
Code example:
$num = 1234567; $format_num = number_format($num); echo $format_num; // 输出 "1,234,567"
Code sample:
$money = 1234.56; $format_money = money_format('%.2n', $money); echo $format_money; // 输出 "1,234.56"
Summary:
Conversion and formatted output of variable types in PHP can help developers process data and output results. Conversion between different types can be easily achieved through casts and built-in functions. At the same time, reasonable formatted output can make the data more beautiful and easy to read, and meet different display needs. The above is a brief introduction and code examples of variable type conversion and formatted output in PHP. I hope it will be helpful to your study and work.
The above is the detailed content of Conversion and formatted output of variable types in PHP. For more information, please follow other related articles on the PHP Chinese website!