Home >Backend Development >PHP Problem >How to convert php string into associative array

How to convert php string into associative array

PHPz
PHPzOriginal
2023-04-18 10:17:46793browse

In PHP, we often need to convert strings into associative arrays for data manipulation and processing. This article will introduce several methods to convert PHP strings into associative arrays.

  1. Use the explode() function

The explode() function splits the string into an array, and the delimiter and string can be passed in as parameters. We can use this function to split the string into the form of $key=>$value, as shown below:

$str = "name=John&age=25&city=NewYork";

// 分割字符串
$arr1 = explode("&", $str);
foreach($arr1 as $val){
    $arr2 = explode("=", $val);
    $result[$arr2[0]] = $arr2[1];
}
print_r($result);

The output result is:

Array
(
    [name] => John
    [age] => 25
    [city] => NewYork
)
  1. Use the parse_str() function

The parse_str() function parses a string into a variable and assigns its value to an array, passing in the form $key=>$value as a parameter. The following is an example of using the parse_str() function:

$str = "name=John&age=25&city=NewYork";
parse_str($str,$result);
print_r($result);

The output result is:

Array
(
    [name] => John
    [age] => 25
    [city] => NewYork
)
  1. Using regular expressions

We can use regular expressions Formula to match a string and then store the result in an associative array. The following is an example of using the preg_match_all() function:

$str = "name=John&age=25&city=NewYork";

preg_match_all('/([^&=]+)=([^&]*)/', $str, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
    $result[$match[1]] = $match[2];
}

print_r($result);

The output result is:

Array
(
    [name] => John
    [age] => 25
    [city] => NewYork
)

Summary

This article introduces three ways to convert PHP strings into associative arrays method. Use these methods to quickly convert strings into arrays and perform data processing and operations. In actual development, we can choose different methods for string conversion according to needs.

The above is the detailed content of How to convert php string into associative array. 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