Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

parse_str()

Synopsis

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

QUERY_STRING is the literal text sent after the question mark in a HTTP GET request, which means that if the page requested was mypage.php?foo=bar&bar=baz, QUERY_STRING is set to foo=bar&bar=baz. The parse_str() function is designed to take a query string like that one and convert it to variables in the same way that PHP does when variables come in. The difference is that variables parsed using parse_str() are converted to global variables, as opposed to elements inside $_GET. So:

    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 />";
    }

That will print out Foo is unset followed by Foo is bar, because the call to parse_str() will set $foo to bar and $bar to baz. Optionally, you can pass an array as the second parameter to parse_str(), and it will put the variables into there. That would make the script look like this:

    $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 />";
    }

That script has the same output as before, except that the variables in the query string are placed into $array. As you can see, the variable names are used as keys in the array, and their values are ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page