Home  >  Article  >  Backend Development  >  How to convert data to different formats using PHP built-in functions?

How to convert data to different formats using PHP built-in functions?

PHPz
PHPzOriginal
2024-04-22 14:15:021028browse

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 内置函数将数据转换为不同格式?

How to use PHP built-in functions to convert data Converting to different formats

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.

Practical case

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}'

More built-in functions

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 bases
  • parse_url(): Parse the URL into its components
  • htmlspecialchars(): Convert HTML characters to HTML entities
  • strip_tags(): Remove HTML and PHP tags from strings

The 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn