PHP Function Reference

PHP parse_str() Function



The PHP parse_str() function parses the string into variables. It parses string as if it were the query string passed via a URL and sets variables in the current scope (or in the array if result is provided).

Syntax

parse_str(string, result)

Parameters

string Required. Specify the input string.
result Optional. (Required as of PHP 8.0.0) Specify the name of an array to store the variables as array elements.

Note: Using this function without the result parameter is DEPRECATED as of PHP 7.2. Since PHP 8.0.0, the result parameter is no longer optional.

Return Value

No value is returned.

Example: parse_str() example

The example below shows the usage of parse_str() function.

<?php
$str = "name=John&city[]=New+York&city[]=London";

//parsing the string
parse_str($str, $output);

//displaying the result
print_r($output);

echo "\n";

//accessing elements of output array
echo $output['name']."\n"; 
echo $output['city'][0]."\n"; 
echo $output['city'][1]."\n"; 
?>

The output of the above code will be:

Array
(
    [name] => John
    [city] => Array
        (
            [0] => New York
            [1] => London
        )

)

John
New York
London

Example: parse_str() name mangling

As variables in PHP can not have dots and spaces in their names, those are converted to underscores. Same applies to naming of respective key names in case of using this function with result parameter. Consider the example below:

<?php
$str = "person name=John&person age=25";

//parsing the string
parse_str($str, $output);

//displaying the result
print_r($output);
?>

The output of the above code will be:

Array
(
    [person_name] => John
    [person_age] => 25
)

❮ PHP String Reference