In PHP development, arrays and strings are very common as two data types. When we need to convert an array into a string, usually we need to convert the array into a "original format string".
To convert the original format of the array into a string, we can use the serialize() function and json_encode() function in the PHP standard library.
The previously mentionedserialize()
function is used to serialize variables. Serialization is the process of converting an object or array and its member variables into individual strings. If the variable is a string, theserialize()
function will simply return a string that has been serialized without converting it like an array or object.
An example of using theserialize()
function to convert an array into a string is as follows:
$arr = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry'); $ser_arr = serialize($arr); echo $ser_arr;
The output result is as follows:
a:3:{s:1:"a";s:5:"apple";s:1:"b";s:6:"banana";s:1:"c";s:6:"cherry";}
The above result is a A string with a, b, and c as key names, and its key values are "apple", "banana" and "cherry" respectively. The "s", "a" and "b" in the output result are additional information added during serialization and are used to reconstruct the original array during deserialization.
Thejson_encode()
function in the PHP standard library can convert PHP arrays and objects into json format strings , allowing data to be transmitted on different platforms.
An example of using thejson_encode()
function to convert an array into a string is as follows:
$arr = array('a' => 'apple', 'b' => 'banana', 'c' => 'cherry'); $json_arr = json_encode($arr); echo $json_arr;
The output results are as follows:
{"a":"apple","b":"banana","c":"cherry"}
andserialize Compared with the results generated by the ()
function, the results generated byjson_encode()
are simpler and easier to read and process.
Summary:
This article introduces how to convert an array into a string using theserialize()
function and thejson_encode()
function in PHP . In actual PHP development, we can choose the appropriate way to transfer and process data according to actual needs.
The above is the detailed content of How to convert array to string in php (two methods). For more information, please follow other related articles on the PHP Chinese website!