Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I turn a string below into an array?

pg_id=2&parent_id=2&document&video 

This is the array I am looking for,

array(
'pg_id' => 2,
'parent_id' => 2,
'document' => ,
'video' =>
)
share|improve this question

5 Answers 5

up vote 56 down vote accepted

You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

 $get_string = "pg_id=2&parent_id=2&document&video";

 parse_str($get_string, $get_array);

 print_r($get_array);
share|improve this answer

Using parse_str().

$str = 'pg_id=2&parent_id=2&document&video';
parse_str($str, $arr);
print_r($arr);
share|improve this answer

There are several possible methods, but for you, there is already a builtin function

$array = array();
parse_str($string, $array);
var_dump($array);
share|improve this answer

Use http://us1.php.net/parse_str

Attention, it's:

parse_str($str, &$array)

not

$array = parse_str($str);.

share|improve this answer

You can simply use http_build_query (Documentation)

<?php

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

echo http_build_query($data) . "\n";
echo http_build_query($data, '', '&amp;');

?>
share|improve this answer
    
This answers the opposite question. He wants to turn a query string into an array, not the other way around. –  Mark Amery Jan 29 at 16:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.