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.
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><?php
$str = "first=php&arr[]=foobar&arr[]=baz&info=.cn";
parse_str($str, $output);
echo $output['first']; // php
echo "<br>";
echo $output['arr'][0]; // foobar
echo "<br>";
echo $output['arr'][1]; // baz
echo "<br>";
echo $output['info']; // .cn
echo "<br>";
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><?php
$str = "first=php&arr[]=foobar&arr[]=baz&info=.cn";
parse_str($str);
echo $first . "<br>";
echo $arr[0] . "<br>";
echo $arr[1] . "<br>";
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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.