Parsing a string into variables

void parse_str ( string input [, array store])

Previously we looked at a handful of the variables set for you inside the superglobal arrays, of which one was QUERY_STRING. If you recall, this 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:

<?php
    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:

<?php
    $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 outputs the same as before, except that the variables found 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 used as the array values.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Regular expressions >>

Previous chapter: Complex string printing

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.