Home > Article > Backend Development > How to use PHP functions for data conversion and formatted output?
How to use PHP functions for data conversion and formatted output?
In PHP, functions are very important tools that can be used for data processing and formatted output. This article will introduce some commonly used PHP functions and how to use them for data conversion and formatted output.
1. Data conversion function
$str = "123"; $int = intval($str); echo $int; // 输出:123 $str2 = "abc"; $int2 = intval($str2); echo $int2; // 输出:0
$str = "3.14"; $float = floatval($str); echo $float; // 输出:3.14 $str2 = "abc"; $float2 = floatval($str2); echo $float2; // 输出:0
$num = 123; $str = strval($num); echo $str; // 输出:123 $bool = true; $str2 = strval($bool); echo $str2; // 输出:1
2. Formatted output function
$num = 12345.6789; $formatted = number_format($num, 2, ".", ","); echo $formatted; // 输出:12,345.68
$name = "John"; $age = 30; $message = sprintf("My name is %s and I am %d years old.", $name, $age); echo $message; // 输出:My name is John and I am 30 years old.
$date = date("Y-m-d H:i:s"); echo $date; // 输出:2022-01-01 12:00:00
3. Comprehensive application
The following is an example of a comprehensive application that demonstrates how to convert a string input by the user into an integer and format the output.
$input = $_POST['input']; // 假设用户输入的字符串为 "1234" $int = intval($input); // 将字符串转换为整数 $formatted = number_format($int, 2, ".", ","); // 格式化输出 echo $formatted; // 输出:1,234.00
The above is an introduction to how to use PHP functions for data conversion and formatted output. Hopefully these examples will help you better understand and apply PHP functions.
The above is the detailed content of How to use PHP functions for data conversion and formatted output?. For more information, please follow other related articles on the PHP Chinese website!