PHP parse_str() Function

Definition

The parse_str() function converts query string to variables. It has the following format.

Syntax

PHP parse_str() Function has the following syntax.

void parse_str ( string str [, array &arr] )

Parameter

PHP parse_str() Function has the following syntax.

  • str - The input string.
  • arr - Optional. If present, variables are stored in this variable as array elements instead.

Return

No value is returned.

Example 1

For example, for URL like mypage.php?foo=bar&bar=baz, Query string is set to foo=bar&bar=baz.

Variables parsed using parse_str() are converted to global variables.


<?PHP//from  w ww  . j a v  a 2 s  . co m
if (isset($foo)) { 
       print "Foo is $foo<br />"; 
} else { 
       print "Foo is unset<br />"; 
} 

parse_str("foo=bar&bar=baz"); 

if (isset($foo)) { 
       print "Foo is $foo<br />"; 
} else { 
       print "Foo is unset<br />"; 
} 
?>

The code above generates the following result.

Example 2

Optionally, we can pass an array as the second parameter to parse_str(), and it will put the variables into there.


<?PHP/*from  ww w .j  a va 2s  .  c  o m*/
$array = array(); 

if (isset($array['foo'])) { 
       print "Foo is {$array['foo']}<br />"; 
} else { 
       print "Foo is unset<br />"; 
} 
parse_str("foo=bar&bar=baz", $array); 
if (isset($array['foo'])) { 
        print "Foo is {$array['foo']}<br />"; 
} else { 
        print "Foo is unset<br />"; 
} 
?>

As we can see, the variable names are used as keys in the array, and their values are used as the array values.

The code above generates the following result.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions