Backend Development 3 min read

Understanding PHP parse_str() Function and Its Usage

This article explains PHP's parse_str() function, detailing its syntax, parameters, and return behavior, and provides two practical examples—one with the optional result array and another using the deprecated single‑parameter form—illustrating how to convert query strings into variables.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP parse_str() Function and Its Usage

When a PHP string contains multiple variable values (e.g., a URL query string), the parse_str() function can parse the string and assign each variable to a PHP variable or array.

The syntax of parse_str() is:

<code>parse_str(string $string, array &$result)</code>

Parameters:

$string : The input string to be parsed.

$result : If provided, the parsed variables are stored as elements of this array; starting with PHP 7.2, omitting this parameter is deprecated.

Return value: The function does not return a value.

Example 1 – Using the second parameter (recommended):

<code>&lt;?php
$str = "first=php&amp;arr[]=foobar&amp;arr[]=baz&amp;info=.cn";
parse_str($str, $output);

echo $output['first'];  // php
echo "&lt;br&gt;";

echo $output['arr'][0]; // foobar
echo "&lt;br&gt;";

echo $output['arr'][1]; // baz
echo "&lt;br&gt;";

echo $output['info'];   // .cn
echo "&lt;br&gt;";
print_r($output);
?>
</code>

The output will be:

<code>php
foobar
baz
.cn
Array ( [first] => php [arr] => Array ( [0] => foobar [1] => baz ) [info] => .cn )</code>

Example 2 – Using only one parameter (deprecated in PHP 7.2):

<code>&lt;?php
$str = "first=php&amp;arr[]=foobar&amp;arr[]=baz&amp;info=.cn";
parse_str($str);

echo $first . "&lt;br&gt;";

echo $arr[0] . "&lt;br&gt;";

echo $arr[1] . "&lt;br&gt;";

echo $info[0];
?>
</code>

In PHP 7.2, calling parse_str() without the second argument triggers an E_DEPRECATED warning, and in PHP 8.0 the $result argument becomes mandatory, so the single‑parameter usage is not recommended.

web developmentPHPstring parsingparse_str
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.