Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
communitycreator

What is the parse_str() function in PHP?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

As a little refresher, you may have seen some query URL that looks like this:

roll_no=2&year=2nd&gpa=8.3

If you have such a URL saved in a variable, you may need to extract the variables and save them separately or as a key-value pair.

The parse_str() function

The parse_str() function is a built-in function in PHP that parses a query string into variables. This function takes URL-like strings and parses them into a variable that can be used in further manipulations.

Syntax

parse_str($aString, $AnArray)

Parameters

  • The first parameter passed is the string that is in a query format. This query string will ultimately be parsed into a variable.

  • The second parameter is optional. It is an array into which the result of the parser function can be stored in a key-value pair.

Return value

No value is returned by the function.

Code

<?php
    // no parsing into array  
    parse_str("sports=soccer&players=22");
    echo $sports."\n".$players;
?>
<?php
     // Now we save the result in an array
    parse_str("fruit=apple&nutrient=30&preference=10.3", $resultArray);
    //display the array content
    print_r($resultArray);
?>

From the two code snippets, we can see how these strings are made to become real variables and these variables are saved in the second snippet in an array.

RELATED TAGS

php
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring