PHP parse_str() Function
In this chapter you will learn:
- Definition for PHP parse_str() Function
- Syntax for PHP parse_str() Function
- Parameter for PHP parse_str() Function
- Return for PHP parse_str() Function
- Example - Parse URL parameter to variables
- Example - Put value to an array
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 ja va 2 s . c o 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// j ava 2 s . c om
$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.
Next chapter...
What you will learn in the next chapter:
- Definition for PHP print() Function
- Syntax for PHP print() Function
- Parameter for PHP print() Function
- Return for PHP print() Function
- Example - Write some text to the output:
- Example - Write the value of the string variable ($str) to the output, including HTML tags
- Example - Join two string variables together
- Example - Write the value of an array to the output