Current Location: Home> Latest Articles> How to Use the parse_str Method in PHP to Parse Strings and URL Parameters

How to Use the parse_str Method in PHP to Parse Strings and URL Parameters

gitbox 2025-06-13

What is the parse_str Method in PHP

In PHP, the parse_str method is used to parse a string into variables and can assign them as global variables. This method is very useful in web development, especially when extracting parameter values from GET or POST request URLs or form inputs.

Basic Syntax of parse_str Method

The basic syntax of the parse_str method is as follows:

parse_str(string $str, array &$arr = array()): bool

Here, $str is the string to be parsed, and $arr is the associative array that stores the parsed results.

Example

Assume we have the following URL:

http://example.com/index.php?key=value&name=Tom&age=25

Using the parse_str method, we can parse the parameters into an associative array:

$url = 'http://example.com/index.php?key=value&name=Tom&age=25';
parse_str(parse_url($url, PHP_URL_QUERY), $params);

The resulting $params array would look like this:

array(
  'key' => 'value',
  'name' => 'Tom',
  'age' => '25'
)

Detailed Usage of parse_str Method

Parsing URL Parameters into Variables

We can parse the URL parameters directly into individual PHP variables. Consider the following URL:

http://example.com/index.php?key=value&name=Tom&age=25

By using the parse_str method, the parameters are converted into PHP variables:

$url = 'http://example.com/index.php?key=value&name=Tom&age=25';
parse_str(parse_url($url, PHP_URL_QUERY));
echo $key;  // Output: value
echo $name; // Output: Tom
echo $age;  // Output: 25

Parsing a String into an Associative Array

We can also directly parse a URL parameter string into an associative array. For example:

$str = 'key=value&name=Tom&age=25';
parse_str($str, $params);
print_r($params);

The output would be:

Array
(
  [key] => value
  [name] => Tom
  [age] => 25
)

Precautions When Using the parse_str Method

When using the parse_str method, the following issues should be noted:

  • If the parsed string contains duplicate keys, only the last key-value pair will be kept.
  • If the parsed variable name conflicts with an existing variable, the new variable will overwrite the existing one.
  • If the variable name contains square brackets, a multidimensional array will be created.

Conclusion

The parse_str method in PHP is a powerful tool for parsing URL parameters or query strings into variables or associative arrays. It simplifies parameter extraction and processing. However, developers should be mindful of potential variable name conflicts to avoid unintended overwrites.