In PHP, strings and arrays are two different types of data structures. When we need to convert a string into an array object, we can use some functions provided by PHP to achieve this. This article will explain how to convert a string to an array object using PHP.
1. Use the explode function
The explode() function can cut a string into an array. This function accepts two parameters, the first parameter is the delimiter used to cut the string, and the second parameter is the string to be cut. The following is an example code that uses the explode() function to convert a comma-separated string into an array:
$str = "apple,banana,orange"; $arr = explode(",", $str); print_r($arr);
This code will output the following:
Array ( [0] => apple [1] => banana [2] => orange )
2. Use the str_split function
The str_split() function can split a string into an array. This function accepts two parameters, the first parameter is the string to be split, and the second parameter is the length of each element. The following is an example code that uses the str_split() function to convert a string into an array:
$str = "hello"; $arr = str_split($str); print_r($arr);
This code will output the following:
Array ( [0] => h [1] => e [2] => l [3] => l [4] => o )
3. Use the preg_split function
The preg_split() function can split a string into an array. This function supports the use of regular expressions to split strings. The following is a sample code that converts a space-delimited string into an array:
$str = "hello world"; $arr = preg_split("/\s/", $str); print_r($arr);
This code will output the following:
Array ( [0] => hello [1] => world )
4. Use the json_decode function
If the string is stored in JSON format, you can use the json_decode() function to convert it into a PHP array. The following is a sample code that converts a JSON string into a PHP array:
$str = '{"name": "Tom", "age": 18}'; $arr = json_decode($str, true); print_r($arr);
This code will output the following content:
Array ( [name] => Tom [age] => 18 )
Note: The json_decode() function returns an object by default. If you need to return an array, you need to set the second parameter to true.
Summary
This article introduces how to use PHP to convert a string into an array object. Different functions can be selected for conversion in different scenarios. When you need to convert a comma-delimited string into an array, you can use the explode() function; when you need to split a string into a fixed-length array, you can use the str_split() function; when you need to use regular expressions to When splitting a string, you can use the preg_split() function; when you need to convert a JSON string into a PHP array, you can use the json_decode() function.
The above is the detailed content of How to convert string to array object in php. For more information, please follow other related articles on the PHP Chinese website!