Home > Article > Backend Development > How to convert data to different formats using PHP built-in functions?
PHP built-in functions can be used to perform the following data conversions: Number format conversion: decimal to octal (decoct()), decimal to hexadecimal (dechex()) String conversion to array: split characters by delimiter String (explode()) Convert JSON string to array (json_decode()) Convert array to JSON string (json_encode())
PHP provides a wide range of built-in functions for converting data from one format to another. Understanding these functions is critical to effectively processing data in a variety of scenarios.
Convert numbers to other bases
Use the decoct()
function to convert decimal numbers to octal :
$num = 123; $octal = decoct($num); // 173
Convert decimal number to hexadecimal using dechex()
function:
$hex = dechex($num); // 7b
Convert string to array
Use the explode()
function to split the string into an array by a specific delimiter:
$str = "PHP,MySQL,Laravel"; $arr = explode(",", $str); // ["PHP", "MySQL", "Laravel"]
Convert a JSON string to an array
Use json_decode()
function to convert JSON string to PHP array:
$json = '{"name":"John", "age":30}'; $arr = json_decode($json, true); // ["name" => "John", "age" => 30]
Convert array to JSON string
Use json_encode()
Function converts PHP array to JSON string:
$arr = ["name" => "John", "age" => 30]; $json = json_encode($arr); // '{"name":"John","age":30}'
PHP provides more useful data conversion functions:
strval()
: Convert the variable to a string intval()
: Convert the variable to an integer floatval()
: Convert the variable to a floating point number boolval()
: Convert the variable to a Boolean value base_convert()
: Convert numbers between different basesparse_url()
: Parse the URL into its componentshtmlspecialchars()
: Convert HTML characters to HTML entitiesstrip_tags()
: Remove HTML and PHP tags from stringsThe above is the detailed content of How to convert data to different formats using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!