Lesser known PHP functions – parse_str

Continuing my Lesser Known PHP Functions series, today’s function is parse_str. This function is an intriguing one as a web developer I often deal with URL strings that return as one string through the way I have my htaccess file set up.

Instead of using expode(), str_replace(), etc to get my URL variables, I can now use parse_str and get the variable information back in array format.

Usage of parse_str is as follows:

$str = "first=value&bar=baz&biz=foo";
parse_str($str, $output);

parse_str has two mandatory parameters, the input string ($str) and an array($output) where the string is broken up into array elements.

Doing a print_r on the above statement returns:

Array
(
    [first] => value
    [bar] => baz
    [biz] => foo
)

Also an interesting note about this function is that if you have a period portion your string that pertains the the array index it will convert the period to an underscore. For example

$str = "foo.bar=value";
parse_str($str, $output);

Outputs:

Array
{
    [foo_bar] => value
)

I guess this function could also be classified as lesser used, since we can use $_GET to retrieve most URL parameters.

Please share or bookmark this post!
  • email
  • DZone
  • Twitter
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Slashdot
  • Netvibes
  • Technorati
  • Google Bookmarks
  • Fark
  • HackerNews
  • Suggest to Techmeme via Twitter
  • Tumblr
  • Add to favorites
  • RSS
Posted by Shawn | Comments (0)

Leave a Reply