1. Code
  2. Coding Fundamentals

How to Use parse_str in PHP

Scroll to top
4 min read

In this article, we’ll explore the parse_str function in PHP. It’s used to convert a GET request query string into usable variables.

In your day-to-day PHP development, you often need to deal with query strings—the way data is passed to your script in the URL on a GET request. When a query string is passed in the URL, PHP provides the super-global $_GET variable containing all the query parameters as PHP variables, so you can easily read the parameters available in the query string. However, sometimes you need to process a raw query string and convert it into variables.

In PHP, there are a couple of different ways that you can achieve this. You can use the explode function to split the query string by the & character and then again by the = character. But there is an even easier way: PHP provides the parse_str function, which allows you to parse the query string in a single call.

Today, we’ll discuss the parse_str function in detail, along with a couple of real-world examples.

Syntax: The parse_str Function

Let’s have a look at the syntax of the parse_str function:

1
parse_str(string $string, array &$result): void

As you can see, parse_str takes two arguments. The first argument is the input string, and it’s expected to be in query string format, e.g. name=wilson&color=blue

The second argument is an array which will be populated by the parsed variables from the query string.

It’s important to note that the parse_str function doesn’t return anything, so you must use the second argument to initialize the result of this function. Until PHP 7.2 the second argument was optional, and omitting it told parse_str to return the result values as variables in the local scope, but as of PHP 7.2 this is a mandatory argument.

Also, the parse_str function always decodes URL-encoded variables, so you don’t need to use the urldecode function. Apart from this, if you have a very long input query string, it may throw the input variables exceeded X error. In that case, check the max_input_vars configuration value in your php.ini configuration file and adjust it as per your requirements.

Let's look at a couple of real-world examples in the next section.

Real-World Examples of parse_str

In this section, we’ll look at a couple of real-world examples to demonstrate how to use the parse_str function.

A Simple Example

Let’s start with a simple example, as shown in the following snippet.

1
<?php
2
$string = 'first_name=John&last_name=Richards&age=30';
3
parse_str($string, $result);
4
print_r($result);
5
6
/**

7
Output:

8
Array

9
(

10
    [first_name] => John

11
    [last_name] => Richards

12
    [age] => 30

13
)

14
**/

As you can see, the parse_str function parses the $string query string, and the $result is populated with an array. Variable names are converted to array keys, and variable values are assigned to the corresponding array keys.

Example With an Array

Oftentimes, the input query string may contain array variables, and the parse_str function can detect it and convert it into the corresponding array variables.

1
<?php
2
$string = 'foo=1&bar[]=1&bar[]=2';
3
parse_str($string, $result);
4
print_r($result);
5
/**

6
$result Output:

7
Array

8
(

9
    [foo] => 1

10
    [bar] => Array

11
        (

12
            [0] => 1

13
            [1] => 2

14
        )

15


16
)

17
**/

As you can see in the example above, the bar variable contains multiple values in the input query string, and it’s converted into the corresponding $result['bar'] array, as shown in the output.

Be careful—if you don't use the special [] syntax after array variables, parse_str will treat it as a regular variable and will only keep the last value in the string. This works a bit differently to most query string parsers.

Example With Special Characters

Sometimes, the input query string contains spaces and dots as a part of the variable names. However, PHP doesn’t allow spaces and dots in variable names, so they are automatically converted to underscores by the parse_str function.

Let’s have a look at the following example to understand how it works.

1
<?php
2
$string = 'my name=John&my.email=john@example.com';
3
parse_str($string, $result);
4
print_r($result);
5
/**

6
$result Output:

7
Array

8
(

9
    [my_name] => John

10
    [my_email] => john@example.com

11
)

12
**/

If you’ve noticed, the space and dot characters in the input query string variables are replaced with the underscore (_) character in the array keys.

Example With URL-Encoded Values

As we discussed earlier, the parse_str function always decodes URL-encoded values during parsing. That means you don’t need to separately apply the urldecode function.

Here's an example with some URL-encoded values.

1
<?php
2
$string = 'name=John%20Richards&profile_url=http%3A%2F%2Fexample.com%2Fmyprofile';
3
parse_str($string, $result);
4
print_r($result);
5
/**

6
$result Output:

7
Array

8
(

9
    [name] => John Richards

10
    [profile_url] => https://example.com/myprofile

11
)

12
**/

As you can see, the URL-encoded characters are automatically converted to their corresponding characters.

Conclusion

Today, we discussed the parse_str function in PHP, which is useful to convert a query string into variables. I hope you find it useful in your own PHP coding!

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.