Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PHP String parse_str() Function



The PHP String parse_str() function is used to convert a query string into variables. The query string sent over a URL is the format of the string that is given to this function for parsing.

Using this function without the result parameter is strongly discouraged and deprecated as of PHP 7.2. As of PHP 8.0.0, the result parameter is required.

Syntax

Below is the syntax of the PHP String parse_str() function −

void parse_str ( string $string, array &$result )

Parameters

Here are the parameters of the parse_str() function −

  • $string − It is the input string.

  • $result − If the second argument result is present, variables are stored in this variable as array items instead.

Return Value

The parse_str() function does not return any value.

PHP Version

First introduced in core PHP 4, the parse_str() function continues to function easily in PHP 5, PHP 7, and PHP 8.

Example 1

First we will show you the basic example of the PHP String parse_str() function to get the information about the last transfer.

<?php
   $string = "name=Amit&age=30";
   parse_str($string, $result);
   print_r($result);
?>

Output

Here is the outcome of the following code −

Array
(
   [name] => Amit
   [age] => 30
)

Example 2

In the below PHP code we will use the parse_str() function and show you how this function works when the query string has not present or empty values.

<?php
   $string = "name=&age=30";
   parse_str($string, $result);
   print_r($result);
?> 

Output

This will generate the below output −

Array
(
   [name] => 
   [age] => 30
)

Example 3

Now the below code using the parse_str() function, we will parse a query string with nested values with the help of array notation.

<?php
   $string = "user[name]=Amita&user[age]=28&user[city]=Mumbai";
   parse_str($string, $result);
   print_r($result);
?> 

Output

This will create the below output −

Array
(
   [user] => Array
      (
         [name] => Amita
         [age] => 28
         [city] => Mumbai
      )
)

Example 4

In the following example, we are using the parse_str() function to parse data in the query string using special characters, like %20 for space.

<?php
   $string = "title=Hello%20Tutorialspoint&description=This%20is%20a%20PHP%20Tutorial.";
   parse_str($string, $result);
   print_r($result);
?> 

Output

Following is the output of the above code −

 Array
(
   [title] => Hello Tutorialspoint
   [description] => This is a PHP Tutorial.
)
php_function_reference.htm
Advertisements