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.

I have come across a unusual scenario where I need to turn a query string into an array.

The query string comes across as:

?sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc

Which decodes as:

sort[0][field]=type&sort[0][dir]=desc

How do I get this into my PHP as a usable array? i.e.

echo $sort[0][field] ; // Outputs "type"

I have tried evil eval() but with no luck.


I need to explain better, what I need is the literal string of sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc to come into my script and stored as a variable, because it will be passed as a parameter in a function.

How do I do that?

share|improve this question
    
You wouldnt want to run eval on a string you are pulling directly from the query string. That would be a massive security flaw. –  gbtimmon Jan 10 '13 at 14:49
add comment

2 Answers

up vote 2 down vote accepted

PHP will convert that format to an array for you.

header("content-type: text/plain");
print_r($_GET);

gives:

Array
(
    [sort] => Array
        (
            [0] => Array
                (
                    [field] => type
                    [dir] => desc
                )

        )

)

If you mean that you have that string as a string and not as the query string input into your webpage, then use the parse_str function to convert it.

header("content-type: text/plain");
$string = "sort%5B0%5D%5Bfield%5D=type&sort%5B0%5D%5Bdir%5D=desc";
$array = Array();
parse_str($string, $array);
print_r($array);

… gives the same output.

share|improve this answer
    
How would i get parse_str() to ignore arrays in the query string? –  imperium2335 Jan 10 '13 at 14:55
    
That's exactly the opposite of what you asked for… use $_SERVER['QUERY_STRING'] if you want to get the raw query string. –  Quentin Jan 10 '13 at 14:57
add comment

Use parse_str()

http://php.net/manual/en/function.parse-str.php

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
vecho $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz


parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>
share|improve this answer
add comment

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.