Current Location: Home> Latest Articles> PHP Variable Type Conversion and Formatting Output Tutorial

PHP Variable Type Conversion and Formatting Output Tutorial

M66 2025-07-02

PHP Variable Type Conversion and Formatting Output Tutorial

In PHP, variables can be converted between different types, which is essential for data processing and result presentation. At the same time, formatted output enhances the readability of data and ensures it meets specific display requirements.

Variable Type Conversion

PHP supports conversion between different data types. Here are some common conversion methods:

String to Integer

To convert a string to an integer, you can use type casting or built-in functions.

$str = "123";

Integer to String

To convert an integer to a string, you can use type casting or built-in functions.

$int = 123;

String to Float

To convert a string to a float, you can use type casting or built-in functions.

$str = "3.14";

Float to String

To convert a float to a string, you can use type casting or built-in functions.

$float = 3.14;

Array to String

To convert an array to a string, you can use the implode() function to join the array elements into a single string.

$arr = array('Hello', 'World');

Formatting Output

Number Formatting

PHP provides the number_format() function for formatting numbers.

$num = 1234.56;

Date Formatting

Use the date() function to format dates and times.

$date = date('Y-m-d H:i:s');

Thousands Separator

Use the number_format() function to add a thousands separator.

$num = 1234567;

Currency Formatting

Use the money_format() function to format currency.

$money = 1234.56;

Conclusion

PHP's variable type conversion and formatting output features provide developers with powerful tools for flexible data type handling and presentation. I hope the code examples above help you better understand and apply these features in your projects.