Home » PHP

PHP: Parse Unparse String Array

1 July 2010 1,238 views Popularity: 3% Share/Bookmark

email

Here is a quick tip on parsing and unparsing string and array in PHP.

You can parses the string into variables by using the parse_str PHP function.

Using parse_str function

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

$str = The input string.
$arr = If the second parameter arr is present, variables are stored in this variable as array elements instead.

Using single parameter

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $data);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

Using the second parameter

$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str, $data);
echo "<pre>"; print_r($data); echo "</pre>";

The output will be:-

Array
(
    [first] => value
    [arr] => Array
        (
            [0] => foo bar
            [1] => baz
        )

)

You can unparse any array into string using the http_build_query function. This generates a URL-encoded query string from the associative (or indexed) array provided.

$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data); // foo=bar&baz=boom&cow=milk&php=hypertext+processor
echo http_build_query($data, '', '&amp;'); // foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

Hope this helps. Thanks.

Related posts:

  1. Random number, string generation in PHP
  2. How to change the source code and modify/parse a website?
  3. PHP: Generating Multiple Random String
  4. PHP: How to get integer or decimal from a string?
  5. PHP Javascript : Playing with multi-dimensional array
  6. PHP: Simple and easy way to format URL string
  7. jQuery: How to replace string, div content and image src?
  8. jQuery: Print array and object
  9. Fun with strings in PHP (Part 1)
  10. PHP : Read Write Xml with SimpleXML
  • http://topsy.com/blog.chapagain.com.np/php-parse-unparse-string-array/?utm_source=pingback&utm_campaign=L2 Tweets that mention PHP: Parse Unparse String Array | Mukesh Chapagain’s Blog — Topsy.com

    [...] This post was mentioned on Twitter by Joonkiri J, Tech Blog. Tech Blog said: PHP: Parse Unparse String Array (http://bit.ly/cpSdbM) #array #parse #PHP #string [...]

  • http://animaux.tweb.fr/771/array-113/ Array | Animaux

    [...] PHP: Parse Unparse String Array | Mukesh Chapagain's Blog [...]