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: parse_str(string $string, array &$result) 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):

<?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);
?>

The output will be:

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

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

<?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];
?>

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendString 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

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.