Current Location: Home> Latest Articles> Comprehensive Guide to Common PHP Data Conversion Functions with Examples

Comprehensive Guide to Common PHP Data Conversion Functions with Examples

M66 2025-09-19

String Conversion Functions

intval(): Convert a string to an integer

$str = "123";
$int = intval($str);
echo $int; // Output: 123

strval(): Convert an integer to a string

$int = 123;
$str = strval($int);
echo $str; // Output: "123"

Array Conversion Functions

implode(): Join array elements into a string

$array = array("apple", "banana", "orange");
$str = implode(", ", $array);
echo $str; // Output: "apple, banana, orange"

explode(): Split a string into array elements

$str = "apple, banana, orange";
$array = explode(", ", $str);
print_r($array); // Output: Array ( [0] => apple [1] => banana [2] => orange )

Type Conversion Functions

floatval(): Convert a string to a float

$str = "3.14";
$float = floatval($str);
echo $float; // Output: 3.14

intval(): Convert a float to an integer

$float = 3.14;
$int = intval($float);
echo $int; // Output: 3

Time Conversion Functions

strtotime(): Convert a date-time string to a timestamp

$date_str = "2022-01-01 12:00:00";
$timestamp = strtotime($date_str);
echo $timestamp; // Output: 1641043200

date(): Format a timestamp as a date-time string

$timestamp = 1641043200;
$date_str = date("Y-m-d H:i:s", $timestamp);
echo $date_str; // Output: "2022-01-01 12:00:00"

Conclusion

The above are commonly used PHP data conversion functions with examples. Mastering these functions allows flexible handling of different data types and improves development efficiency. Whether converting strings, arrays, types, or time values, these functions are essential tools for both beginners and advanced PHP developers to reference and learn.